blob: af451c253f6ccce2c7c7bd05fdb182ac61bd03bb [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
Andrii Kulian88e05cb2017-12-05 17:21:10 -080019import static android.app.servertransaction.ActivityLifecycleItem.ON_CREATE;
20import static android.app.servertransaction.ActivityLifecycleItem.ON_DESTROY;
21import static android.app.servertransaction.ActivityLifecycleItem.ON_PAUSE;
22import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
23import static android.app.servertransaction.ActivityLifecycleItem.ON_START;
24import static android.app.servertransaction.ActivityLifecycleItem.ON_STOP;
25import static android.app.servertransaction.ActivityLifecycleItem.PRE_ON_CREATE;
Andrii Kulianb047b8b2017-02-08 18:38:26 -080026import static android.view.Display.INVALID_DISPLAY;
27
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -070028import android.annotation.NonNull;
29import android.annotation.Nullable;
Mathew Inwood4fb17d12018-08-14 14:25:44 +010030import android.annotation.UnsupportedAppUsage;
Dianne Hackborn69c6adc2015-06-02 10:52:59 -070031import android.app.assist.AssistContent;
32import android.app.assist.AssistStructure;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.BackupAgent;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070034import android.app.servertransaction.ActivityLifecycleItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080035import android.app.servertransaction.ActivityLifecycleItem.LifecycleState;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070036import android.app.servertransaction.ActivityRelaunchItem;
Andrii Kulian446e8242017-10-26 15:17:29 -070037import android.app.servertransaction.ActivityResultItem;
38import android.app.servertransaction.ClientTransaction;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080039import android.app.servertransaction.PendingTransactionActions;
40import android.app.servertransaction.PendingTransactionActions.StopInfo;
41import android.app.servertransaction.TransactionExecutor;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070042import android.app.servertransaction.TransactionExecutorHelper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070044import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ComponentName;
46import android.content.ContentProvider;
47import android.content.Context;
48import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070049import android.content.IIntentReceiver;
Jesse Hall317fa5a2017-05-23 15:46:55 -070050import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.ActivityInfo;
52import android.content.pm.ApplicationInfo;
53import android.content.pm.IPackageManager;
54import android.content.pm.InstrumentationInfo;
Christopher Tate346acb12012-10-15 19:20:25 -070055import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070057import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070058import android.content.pm.ParceledListSlice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.pm.ProviderInfo;
60import android.content.pm.ServiceInfo;
61import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070062import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.content.res.Configuration;
64import android.content.res.Resources;
Alan Viverettee54d2452015-05-06 10:41:43 -070065import android.content.res.Resources.Theme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.database.sqlite.SQLiteDatabase;
67import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080068import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.graphics.Bitmap;
70import android.graphics.Canvas;
Leon Scroggins III8290eab2018-03-19 10:51:44 -040071import android.graphics.ImageDecoder;
Jeff Brownbd6e1502012-08-28 03:27:37 -070072import android.hardware.display.DisplayManagerGlobal;
Paul Jensene0bef712014-12-10 15:12:18 -050073import android.net.ConnectivityManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070074import android.net.IConnectivityManager;
75import android.net.Proxy;
Jason Monk83520b92014-05-09 15:16:06 -040076import android.net.Uri;
Joe Onoratod630f102011-03-17 18:42:26 -070077import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070078import android.os.Binder;
Jeff Sharkey344744b2016-01-28 19:03:30 -070079import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Bundle;
81import android.os.Debug;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070082import android.os.Environment;
Jesse Hallb12249b2016-12-12 12:53:02 -080083import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Handler;
Jeff Sharkey8439ac02017-12-12 17:26:23 -070085import android.os.HandlerExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.IBinder;
Adam Lesinskib61e4052016-05-19 18:23:05 -070087import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.Looper;
89import android.os.Message;
90import android.os.MessageQueue;
Dianne Hackbornfabb70b2014-11-11 12:22:36 -080091import android.os.Parcel;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070092import android.os.ParcelFileDescriptor;
Craig Mautnera0026042014-04-23 11:45:37 -070093import android.os.PersistableBundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.Process;
95import android.os.RemoteException;
96import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070097import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.SystemClock;
Jeff Brownefd43bd2012-09-21 17:02:35 -070099import android.os.SystemProperties;
Dianne Hackborn1ded0b12012-04-26 14:14:50 -0700100import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700101import android.os.UserHandle;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600102import android.provider.BlockedNumberContract;
103import android.provider.CalendarContract;
104import android.provider.CallLog;
105import android.provider.ContactsContract;
106import android.provider.Downloads;
Seigo Nonaka54084b62017-04-24 14:46:23 -0700107import android.provider.FontsContract;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000108import android.provider.Settings;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700109import android.renderscript.RenderScriptCacheDir;
Chad Brubakerc72875b2016-04-27 16:35:11 -0700110import android.security.NetworkSecurityPolicy;
Chad Brubaker78d47122015-11-17 22:26:58 -0800111import android.security.net.config.NetworkSecurityConfigProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.util.AndroidRuntimeException;
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700113import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.util.DisplayMetrics;
115import android.util.EventLog;
116import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700117import android.util.LogPrinter;
Andrii Kulianb372da62018-01-18 10:46:24 -0800118import android.util.MergedConfiguration;
Craig Mautnereb8abf72014-07-02 15:04:09 -0700119import android.util.Pair;
Jeff Brown6754ba22011-12-14 20:20:01 -0800120import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800121import android.util.Slog;
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700122import android.util.SparseIntArray;
Adam Powell14874662013-07-18 19:42:41 -0700123import android.util.SuperNotCalledException;
Kweku Adams598e9a22017-11-02 17:12:20 -0700124import android.util.proto.ProtoOutputStream;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200125import android.view.Choreographer;
Adam Lesinski3ad1b482016-04-01 16:41:41 -0700126import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import android.view.Display;
John Reck51aaf902015-12-02 15:08:07 -0800128import android.view.ThreadedRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.view.View;
130import android.view.ViewDebug;
131import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -0700132import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133import android.view.Window;
134import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700135import android.view.WindowManagerGlobal;
Richard Uhler2c036192016-09-14 09:48:31 +0100136import android.webkit.WebView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700138import com.android.internal.annotations.GuardedBy;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800139import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700140import com.android.internal.app.IVoiceInteractor;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800141import com.android.internal.content.ReferrerIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import com.android.internal.os.BinderInternal;
143import com.android.internal.os.RuntimeInit;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700144import com.android.internal.os.SomeArgs;
Jeff Sharkey3e195892016-03-05 19:48:59 -0700145import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -0700146import com.android.internal.util.FastPrintWriter;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200147import com.android.internal.util.Preconditions;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200148import com.android.internal.util.function.pooled.PooledLambda;
Kenny Root12e75222013-04-23 22:34:24 -0700149import com.android.org.conscrypt.OpenSSLSocketImpl;
Robin Lee3d076af2014-04-25 14:57:49 +0100150import com.android.org.conscrypt.TrustedCertificateStore;
Yi Jin6c6e9ca2018-03-20 16:53:35 -0700151import com.android.server.am.MemInfoDumpProto;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700152
Jesse Hall317fa5a2017-05-23 15:46:55 -0700153import dalvik.system.CloseGuard;
154import dalvik.system.VMDebug;
155import dalvik.system.VMRuntime;
156
Jesse Hall317fa5a2017-05-23 15:46:55 -0700157import libcore.io.IoUtils;
158import libcore.net.event.NetworkEventDispatcher;
159
160import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162import java.io.File;
163import java.io.FileDescriptor;
164import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700165import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166import java.io.PrintWriter;
167import java.lang.ref.WeakReference;
Svet Ganov37e43272016-09-09 16:01:32 -0700168import java.lang.reflect.Field;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400169import java.lang.reflect.Method;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700170import java.net.InetAddress;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000171import java.text.DateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172import java.util.ArrayList;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600173import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174import java.util.List;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700175import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176import java.util.Map;
Kenny Roote6585b32013-12-13 12:00:26 -0800177import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178import java.util.TimeZone;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700179import java.util.concurrent.Executor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700181final class RemoteServiceException extends AndroidRuntimeException {
182 public RemoteServiceException(String msg) {
183 super(msg);
184 }
185}
186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187/**
188 * This manages the execution of the main thread in an
189 * application process, scheduling and executing activities,
190 * broadcasts, and other operations on it as the activity
191 * manager requests.
192 *
193 * {@hide}
194 */
Andrii Kulian446e8242017-10-26 15:17:29 -0700195public final class ActivityThread extends ClientTransactionHandler {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700196 /** @hide */
197 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700198 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700199 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700200 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700201 /** @hide */
202 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700203 private static final boolean DEBUG_RESULTS = false;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700204 private static final boolean DEBUG_BACKUP = false;
Craig Mautner88c05892013-06-28 09:47:45 -0700205 public static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800206 private static final boolean DEBUG_SERVICE = false;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800207 public static final boolean DEBUG_MEMORY_TRIM = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700208 private static final boolean DEBUG_PROVIDER = false;
Andrii Kulianb372da62018-01-18 10:46:24 -0800209 public static final boolean DEBUG_ORDER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Dianne Hackborn455625e2015-01-21 09:55:13 -0800213 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
214 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
215 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
216 public static final int SERVICE_DONE_EXECUTING_START = 1;
217 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
218 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
219
Filip Gruszczynskica664812015-12-04 12:43:36 -0800220 // Whether to invoke an activity callback after delivering new configuration.
221 private static final boolean REPORT_TO_ACTIVITY = true;
222
Sudheer Shanka84a48952017-03-08 18:19:01 -0800223 /**
224 * Denotes an invalid sequence number corresponding to a process state change.
225 */
226 public static final long INVALID_PROC_STATE_SEQ = -1;
227
Sudheer Shankaf6690102017-10-16 10:20:32 -0700228 /**
229 * Identifier for the sequence no. associated with this process start. It will be provided
230 * as one of the arguments when the process starts.
231 */
232 public static final String PROC_START_SEQ_IDENT = "seq=";
233
Sudheer Shanka84a48952017-03-08 18:19:01 -0800234 private final Object mNetworkPolicyLock = new Object();
235
236 /**
237 * Denotes the sequence number of the process state change for which the main thread needs
238 * to block until the network rules are updated for it.
239 *
240 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
241 */
242 @GuardedBy("mNetworkPolicyLock")
243 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
244
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100245 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -0700246 private ContextImpl mSystemContext;
Adam Lesinskia82b6262017-03-21 16:56:17 -0700247 private ContextImpl mSystemUiContext;
Bob Leee5408332009-09-04 18:31:17 -0700248
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100249 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700250 static volatile IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100252 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700253 final ApplicationThread mAppThread = new ApplicationThread();
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100254 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700255 final Looper mLooper = Looper.myLooper();
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100256 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700257 final H mH = new H();
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700258 final Executor mExecutor = new HandlerExecutor(mH);
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100259 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700260 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700261 // List of new activities (via ActivityRecord.nextIdle) that should
262 // be reported when next we idle.
263 ActivityClientRecord mNewActivities = null;
264 // Number of activities that are currently visible on-screen.
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100265 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700266 int mNumVisibleActivities = 0;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700267 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
268 private int mLastSessionId;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100269 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700270 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100271 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700272 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700273 Profiler mProfiler;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100274 @UnsupportedAppUsage
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700275 int mCurDefaultDisplayDpi;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100276 @UnsupportedAppUsage
Dianne Hackborndde331c2012-08-03 14:01:57 -0700277 boolean mDensityCompatMode;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100278 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700279 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700280 Configuration mCompatConfiguration;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100281 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700282 Application mInitialApplication;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100283 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700284 final ArrayList<Application> mAllApplications
285 = new ArrayList<Application>();
286 // set of instantiated backup agents, keyed by package name
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700287 final ArrayMap<String, BackupAgent> mBackupAgents = new ArrayMap<String, BackupAgent>();
Jeff Sharkey66a017b2013-01-17 18:18:22 -0800288 /** Reference to singleton {@link ActivityThread} */
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100289 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700290 private static volatile ActivityThread sCurrentActivityThread;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100291 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700292 Instrumentation mInstrumentation;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700293 String mInstrumentationPackageName = null;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100294 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700295 String mInstrumentationAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700296 String[] mInstrumentationSplitAppDirs = null;
297 String mInstrumentationLibDir = null;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100298 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700299 String mInstrumentedAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700300 String[] mInstrumentedSplitAppDirs = null;
301 String mInstrumentedLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700302 boolean mSystemThread = false;
303 boolean mJitEnabled = false;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700304 boolean mSomeActivitiesChanged = false;
Chong Zhang4951f9d2016-06-23 13:15:08 -0700305 boolean mUpdatingSystemConfig = false;
David Brazdild960cc42018-01-31 07:59:17 +0000306 /* package */ boolean mHiddenApiWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100308 // These can be accessed by multiple threads; mResourcesManager is the lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700309 // XXX For now we keep around information about all packages we have
310 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800311 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700312 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800313 // which means this lock gets held while the activity and window managers
314 // holds their own lock. Thus you MUST NEVER call back into the activity manager
315 // or window manager or anything that depends on them while holding this lock.
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700316 // These LoadedApk are only valid for the userId that we're running as.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100317 @GuardedBy("mResourcesManager")
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100318 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100319 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
320 @GuardedBy("mResourcesManager")
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100321 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100322 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
323 @GuardedBy("mResourcesManager")
324 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
325 @GuardedBy("mResourcesManager")
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100326 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700327 Configuration mPendingConfiguration = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800328 // An executor that performs multi-step transactions.
329 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330
Mathew Inwood45d2c252018-09-14 12:35:36 +0100331 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Craig Mautner88c05892013-06-28 09:47:45 -0700332 private final ResourcesManager mResourcesManager;
333
Jeff Sharkey6d515712012-09-20 16:06:08 -0700334 private static final class ProviderKey {
335 final String authority;
336 final int userId;
337
338 public ProviderKey(String authority, int userId) {
339 this.authority = authority;
340 this.userId = userId;
341 }
342
343 @Override
344 public boolean equals(Object o) {
345 if (o instanceof ProviderKey) {
346 final ProviderKey other = (ProviderKey) o;
Kenny Roote6585b32013-12-13 12:00:26 -0800347 return Objects.equals(authority, other.authority) && userId == other.userId;
Jeff Sharkey6d515712012-09-20 16:06:08 -0700348 }
349 return false;
350 }
351
352 @Override
353 public int hashCode() {
354 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
355 }
356 }
357
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700358 // The lock of mProviderMap protects the following variables.
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100359 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700360 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
361 = new ArrayMap<ProviderKey, ProviderClientRecord>();
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100362 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700363 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
364 = new ArrayMap<IBinder, ProviderRefCount>();
Mathew Inwood45d2c252018-09-14 12:35:36 +0100365 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Wale Ogunwale1d646122015-04-24 14:45:14 -0700366 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
367 = new ArrayMap<IBinder, ProviderClientRecord>();
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100368 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700369 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
370 = new ArrayMap<ComponentName, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371
Makoto Onukib6c79ea2018-05-31 11:03:56 -0700372 // Mitigation for b/74523247: Used to serialize calls to AM.getContentProvider().
373 // Note we never removes items from this map but that's okay because there are only so many
374 // users and so many authorities.
375 // TODO Remove it once we move CPR.wait() from AMS to the client side.
376 @GuardedBy("mGetProviderLocks")
377 final ArrayMap<ProviderKey, Object> mGetProviderLocks = new ArrayMap<>();
378
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700379 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
Wale Ogunwale1d646122015-04-24 14:45:14 -0700380 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
Jeff Hamilton52d32032011-01-08 15:31:26 -0600381
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700382 final GcIdler mGcIdler = new GcIdler();
Tim Murray12f511e2018-10-22 15:26:08 -0700383 final PurgeIdler mPurgeIdler = new PurgeIdler();
384
385 boolean mPurgeIdlerScheduled = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700386 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
Mathew Inwood45d2c252018-09-14 12:35:36 +0100388 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700389 static volatile Handler sMainThreadHandler; // set once in main()
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700390
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800391 Bundle mCoreSettings = null;
392
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800393 /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
394 public static final class ActivityClientRecord {
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100395 @UnsupportedAppUsage
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800396 public IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700397 int ident;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100398 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 Intent intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800400 String referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700401 IVoiceInteractor voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -0700403 PersistableBundle persistentState;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100404 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 Activity activity;
406 Window window;
407 Activity parent;
408 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700409 Activity.NonConfigurationInstances lastNonConfigurationInstances;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800410 // TODO(lifecycler): Use mLifecycleState instead.
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100411 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 boolean paused;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100413 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 boolean stopped;
415 boolean hideForNow;
416 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700417 Configuration createdConfig;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800418 Configuration overrideConfig;
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800419 // Used for consolidating configs before sending on to Activity.
420 private Configuration tmpConfig = new Configuration();
Andrii Kulian44607962017-03-16 11:06:24 -0700421 // Callback used for updating activity override config.
422 ViewRootImpl.ActivityConfigCallback configCallback;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700423 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424
Jeff Hao1b012d32014-08-20 10:35:34 -0700425 ProfilerInfo profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700426
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100427 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 ActivityInfo activityInfo;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100429 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400430 CompatibilityInfo compatInfo;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100431 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000432 public LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433
434 List<ResultInfo> pendingResults;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800435 List<ReferrerIntent> pendingIntents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436
437 boolean startsNotResumed;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800438 public final boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800439 int pendingConfigChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800440
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700441 Window mPendingRemoveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800442 WindowManager mPendingRemoveWindowManager;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100443 @UnsupportedAppUsage
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700444 boolean mPreserveWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800446 @LifecycleState
447 private int mLifecycleState = PRE_ON_CREATE;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700448
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800449 @VisibleForTesting
Mathew Inwood45d2c252018-09-14 12:35:36 +0100450 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800451 public ActivityClientRecord() {
452 this.isForward = false;
453 init();
454 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700455
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800456 public ActivityClientRecord(IBinder token, Intent intent, int ident,
457 ActivityInfo info, Configuration overrideConfig, CompatibilityInfo compatInfo,
458 String referrer, IVoiceInteractor voiceInteractor, Bundle state,
459 PersistableBundle persistentState, List<ResultInfo> pendingResults,
460 List<ReferrerIntent> pendingNewIntents, boolean isForward,
461 ProfilerInfo profilerInfo, ClientTransactionHandler client) {
462 this.token = token;
463 this.ident = ident;
464 this.intent = intent;
465 this.referrer = referrer;
466 this.voiceInteractor = voiceInteractor;
467 this.activityInfo = info;
468 this.compatInfo = compatInfo;
469 this.state = state;
470 this.persistentState = persistentState;
471 this.pendingResults = pendingResults;
472 this.pendingIntents = pendingNewIntents;
473 this.isForward = isForward;
474 this.profilerInfo = profilerInfo;
475 this.overrideConfig = overrideConfig;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000476 this.packageInfo = client.getPackageInfoNoCheck(activityInfo.applicationInfo,
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800477 compatInfo);
478 init();
479 }
480
481 /** Common initializer for all constructors. */
482 private void init() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 parent = null;
484 embeddedID = null;
485 paused = false;
486 stopped = false;
487 hideForNow = false;
488 nextIdle = null;
Andrii Kulian44607962017-03-16 11:06:24 -0700489 configCallback = (Configuration overrideConfig, int newDisplayId) -> {
490 if (activity == null) {
491 throw new IllegalStateException(
492 "Received config update for non-existing activity");
493 }
Andrii Kulian446e8242017-10-26 15:17:29 -0700494 activity.mMainThread.handleActivityConfigurationChanged(token, overrideConfig,
495 newDisplayId);
Andrii Kulian44607962017-03-16 11:06:24 -0700496 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 }
498
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800499 /** Get the current lifecycle state. */
500 public int getLifecycleState() {
501 return mLifecycleState;
502 }
503
504 /** Update the current lifecycle state for internal bookkeeping. */
505 public void setState(@LifecycleState int newLifecycleState) {
506 mLifecycleState = newLifecycleState;
507 switch (mLifecycleState) {
508 case ON_CREATE:
509 paused = true;
510 stopped = true;
511 break;
512 case ON_START:
513 paused = true;
514 stopped = false;
515 break;
516 case ON_RESUME:
517 paused = false;
518 stopped = false;
519 break;
520 case ON_PAUSE:
521 paused = true;
522 stopped = false;
523 break;
524 case ON_STOP:
525 paused = true;
526 stopped = true;
527 break;
528 }
529 }
530
Andrii Kulian391161f2018-01-29 10:50:02 -0800531 private boolean isPreHoneycomb() {
532 return activity != null && activity.getApplicationInfo().targetSdkVersion
533 < android.os.Build.VERSION_CODES.HONEYCOMB;
534 }
535
536 private boolean isPreP() {
537 return activity != null && activity.getApplicationInfo().targetSdkVersion
538 < android.os.Build.VERSION_CODES.P;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800539 }
540
Craig Mautnera0026042014-04-23 11:45:37 -0700541 public boolean isPersistable() {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700542 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
Craig Mautnera0026042014-04-23 11:45:37 -0700543 }
544
Andrii Kulian914aa7d2018-03-19 21:51:53 -0700545 public boolean isVisibleFromServer() {
546 return activity != null && activity.mVisibleFromServer;
547 }
548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 public String toString() {
Dianne Hackbornb61a0262012-05-14 17:19:18 -0700550 ComponentName componentName = intent != null ? intent.getComponent() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 return "ActivityRecord{"
552 + Integer.toHexString(System.identityHashCode(this))
553 + " token=" + token + " " + (componentName == null
554 ? "no component name" : componentName.toShortString())
555 + "}";
556 }
Andrii Kulian58178f22016-03-16 13:44:56 -0700557
558 public String getStateString() {
559 StringBuilder sb = new StringBuilder();
560 sb.append("ActivityClientRecord{");
561 sb.append("paused=").append(paused);
562 sb.append(", stopped=").append(stopped);
563 sb.append(", hideForNow=").append(hideForNow);
564 sb.append(", startsNotResumed=").append(startsNotResumed);
565 sb.append(", isForward=").append(isForward);
566 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
Andrii Kulian58178f22016-03-16 13:44:56 -0700567 sb.append(", preserveWindow=").append(mPreserveWindow);
568 if (activity != null) {
569 sb.append(", Activity{");
570 sb.append("resumed=").append(activity.mResumed);
571 sb.append(", stopped=").append(activity.mStopped);
572 sb.append(", finished=").append(activity.isFinishing());
573 sb.append(", destroyed=").append(activity.isDestroyed());
574 sb.append(", startedActivity=").append(activity.mStartedActivity);
575 sb.append(", temporaryPause=").append(activity.mTemporaryPause);
576 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
Andrii Kulian58178f22016-03-16 13:44:56 -0700577 sb.append("}");
578 }
579 sb.append("}");
580 return sb.toString();
581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 }
583
Wale Ogunwale1d646122015-04-24 14:45:14 -0700584 final class ProviderClientRecord {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700585 final String[] mNames;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100586 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 final IContentProvider mProvider;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100588 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 final ContentProvider mLocalProvider;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100590 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700591 final ContentProviderHolder mHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700593 ProviderClientRecord(String[] names, IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700594 ContentProvider localProvider, ContentProviderHolder holder) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700595 mNames = names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 mProvider = provider;
597 mLocalProvider = localProvider;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700598 mHolder = holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 }
600 }
601
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400602 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700603 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700604 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
605 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
riddle_hsu1f5ac4d2015-01-03 15:38:21 +0800606 token, sendingUser, intent.getFlags());
Dianne Hackborne829fef2010-10-26 17:44:01 -0700607 this.intent = intent;
608 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700609
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100610 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 Intent intent;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100612 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 ActivityInfo info;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100614 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400615 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 public String toString() {
617 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700618 info.packageName + " resultCode=" + getResultCode()
619 + " resultData=" + getResultData() + " resultExtras="
620 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 }
622 }
623
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400624 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700625 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400626 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700627 int backupMode;
628 public String toString() {
629 return "CreateBackupAgentData{appInfo=" + appInfo
630 + " backupAgent=" + appInfo.backupAgentName
631 + " mode=" + backupMode + "}";
632 }
633 }
Bob Leee5408332009-09-04 18:31:17 -0700634
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400635 static final class CreateServiceData {
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100636 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 IBinder token;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100638 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 ServiceInfo info;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100640 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400641 CompatibilityInfo compatInfo;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100642 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 Intent intent;
644 public String toString() {
645 return "CreateServiceData{token=" + token + " className="
646 + info.name + " packageName=" + info.packageName
647 + " intent=" + intent + "}";
648 }
649 }
650
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400651 static final class BindServiceData {
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100652 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 IBinder token;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100654 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 Intent intent;
656 boolean rebind;
657 public String toString() {
658 return "BindServiceData{token=" + token + " intent=" + intent + "}";
659 }
660 }
661
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400662 static final class ServiceArgsData {
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100663 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700665 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700667 int flags;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100668 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 Intent args;
670 public String toString() {
671 return "ServiceArgsData{token=" + token + " startId=" + startId
672 + " args=" + args + "}";
673 }
674 }
675
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400676 static final class AppBindData {
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100677 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000678 LoadedApk info;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100679 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 String processName;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100681 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 ApplicationInfo appInfo;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100683 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 List<ProviderInfo> providers;
685 ComponentName instrumentationName;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100686 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 Bundle instrumentationArgs;
688 IInstrumentationWatcher instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800689 IUiAutomationConnection instrumentationUiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 int debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400691 boolean enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700692 boolean trackAllocation;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100693 @UnsupportedAppUsage
Christopher Tate181fafa2009-05-14 11:12:14 -0700694 boolean restrictedBackupMode;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100695 @UnsupportedAppUsage
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700696 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 Configuration config;
Mathew Inwood45d2c252018-09-14 12:35:36 +0100698 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400699 CompatibilityInfo compatInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700700 String buildSerial;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700701
702 /** Initial values for {@link Profiler}. */
Jeff Hao1b012d32014-08-20 10:35:34 -0700703 ProfilerInfo initProfilerInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700704
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800705 boolean autofillCompatibilityEnabled;
706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 public String toString() {
708 return "AppBindData{appInfo=" + appInfo + "}";
709 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700710 }
711
712 static final class Profiler {
713 String profileFile;
714 ParcelFileDescriptor profileFd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700715 int samplingInterval;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700716 boolean autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800717 boolean streamingOutput;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700718 boolean profiling;
719 boolean handlingProfiling;
Jeff Hao1b012d32014-08-20 10:35:34 -0700720 public void setProfiler(ProfilerInfo profilerInfo) {
721 ParcelFileDescriptor fd = profilerInfo.profileFd;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700722 if (profiling) {
723 if (fd != null) {
724 try {
725 fd.close();
726 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700727 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700728 }
729 }
730 return;
731 }
732 if (profileFd != null) {
733 try {
734 profileFd.close();
735 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700736 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700737 }
738 }
Jeff Hao1b012d32014-08-20 10:35:34 -0700739 profileFile = profilerInfo.profileFile;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700740 profileFd = fd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700741 samplingInterval = profilerInfo.samplingInterval;
742 autoStopProfiler = profilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800743 streamingOutput = profilerInfo.streamingOutput;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700744 }
745 public void startProfiling() {
746 if (profileFd == null || profiling) {
747 return;
748 }
749 try {
Andreas Gampeeff06392016-05-10 12:51:45 -0700750 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
Jeff Hao1b012d32014-08-20 10:35:34 -0700751 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800752 bufferSize * 1024 * 1024, 0, samplingInterval != 0, samplingInterval,
753 streamingOutput);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700754 profiling = true;
755 } catch (RuntimeException e) {
Andreas Gampe4f689242018-03-14 23:13:28 -0700756 Slog.w(TAG, "Profiling failed on path " + profileFile, e);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700757 try {
758 profileFd.close();
759 profileFd = null;
760 } catch (IOException e2) {
761 Slog.w(TAG, "Failure closing profile fd", e2);
762 }
763 }
764 }
765 public void stopProfiling() {
766 if (profiling) {
767 profiling = false;
768 Debug.stopMethodTracing();
769 if (profileFd != null) {
770 try {
771 profileFd.close();
772 } catch (IOException e) {
773 }
774 }
775 profileFd = null;
776 profileFile = null;
777 }
778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 }
780
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400781 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700782 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700783 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800784 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 }
787
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400788 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800789 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 String what;
791 String who;
792 }
793
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400794 static final class DumpHeapData {
Christopher Ferris8d652f82017-04-11 16:29:18 -0700795 public boolean managed;
796 public boolean mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700797 public boolean runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700798 String path;
799 ParcelFileDescriptor fd;
800 }
801
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400802 static final class UpdateCompatibilityData {
803 String pkg;
804 CompatibilityInfo info;
805 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800806
Adam Skorydfc7fd72013-08-05 19:23:41 -0700807 static final class RequestAssistContextExtras {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800808 IBinder activityToken;
809 IBinder requestToken;
810 int requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700811 int sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -0700812 int flags;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800813 }
Anwar Ghuloum3a8ce1b2013-04-26 16:18:28 -0700814
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700815 private class ApplicationThread extends IApplicationThread.Stub {
Vasu Nori3c7131f2010-09-21 14:36:57 -0700816 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700817
Dianne Hackborna413dc02013-07-12 12:02:55 -0700818 private int mLastProcessState = -1;
819
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700820 private void updatePendingConfiguration(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -0700821 synchronized (mResourcesManager) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700822 if (mPendingConfiguration == null ||
823 mPendingConfiguration.isOtherSeqNewer(config)) {
824 mPendingConfiguration = config;
825 }
826 }
827 }
828
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800829 public final void scheduleSleeping(IBinder token, boolean sleeping) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700830 sendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800831 }
832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400834 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700835 boolean sync, int sendingUser, int processState) {
836 updateProcessState(processState, false);
Dianne Hackborne829fef2010-10-26 17:44:01 -0700837 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700838 sync, false, mAppThread.asBinder(), sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400840 r.compatInfo = compatInfo;
Jeff Brown9ef09972013-10-15 20:49:59 -0700841 sendMessage(H.RECEIVER, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
843
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400844 public final void scheduleCreateBackupAgent(ApplicationInfo app,
845 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700846 CreateBackupAgentData d = new CreateBackupAgentData();
847 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400848 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700849 d.backupMode = backupMode;
850
Jeff Brown9ef09972013-10-15 20:49:59 -0700851 sendMessage(H.CREATE_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700852 }
853
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400854 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
855 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700856 CreateBackupAgentData d = new CreateBackupAgentData();
857 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400858 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700859
Jeff Brown9ef09972013-10-15 20:49:59 -0700860 sendMessage(H.DESTROY_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700861 }
862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 public final void scheduleCreateService(IBinder token,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700864 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
865 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 CreateServiceData s = new CreateServiceData();
867 s.token = token;
868 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400869 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870
Jeff Brown9ef09972013-10-15 20:49:59 -0700871 sendMessage(H.CREATE_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 }
873
874 public final void scheduleBindService(IBinder token, Intent intent,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700875 boolean rebind, int processState) {
876 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 BindServiceData s = new BindServiceData();
878 s.token = token;
879 s.intent = intent;
880 s.rebind = rebind;
881
Amith Yamasani742a6712011-05-04 14:49:28 -0700882 if (DEBUG_SERVICE)
883 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
884 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
Jeff Brown9ef09972013-10-15 20:49:59 -0700885 sendMessage(H.BIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 }
887
888 public final void scheduleUnbindService(IBinder token, Intent intent) {
889 BindServiceData s = new BindServiceData();
890 s.token = token;
891 s.intent = intent;
892
Jeff Brown9ef09972013-10-15 20:49:59 -0700893 sendMessage(H.UNBIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
895
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700896 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
897 List<ServiceStartArgs> list = args.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700899 for (int i = 0; i < list.size(); i++) {
900 ServiceStartArgs ssa = list.get(i);
901 ServiceArgsData s = new ServiceArgsData();
902 s.token = token;
903 s.taskRemoved = ssa.taskRemoved;
904 s.startId = ssa.startId;
905 s.flags = ssa.flags;
906 s.args = ssa.args;
907
908 sendMessage(H.SERVICE_ARGS, s);
909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911
912 public final void scheduleStopService(IBinder token) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700913 sendMessage(H.STOP_SERVICE, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 }
915
Jeff Hao1b012d32014-08-20 10:35:34 -0700916 public final void bindApplication(String processName, ApplicationInfo appInfo,
917 List<ProviderInfo> providers, ComponentName instrumentationName,
918 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
919 IInstrumentationWatcher instrumentationWatcher,
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800920 IUiAutomationConnection instrumentationUiConnection, int debugMode,
Pablo Ceballosa4d4e822015-10-05 10:27:52 -0700921 boolean enableBinderTracking, boolean trackAllocation,
922 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700923 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800924 String buildSerial, boolean autofillCompatibilityEnabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925
926 if (services != null) {
Makoto Onuki45895652018-05-07 14:43:05 -0700927 if (false) {
928 // Test code to make sure the app could see the passed-in services.
929 for (Object oname : services.keySet()) {
930 if (services.get(oname) == null) {
931 continue; // AM just passed in a null service.
932 }
933 String name = (String) oname;
934
935 // See b/79378449 about the following exemption.
936 switch (name) {
937 case "package":
938 case Context.WINDOW_SERVICE:
939 continue;
940 }
941
942 if (ServiceManager.getService(name) == null) {
943 Log.wtf(TAG, "Service " + name + " should be accessible by this app");
944 }
945 }
946 }
947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 // Setup the service cache in the ServiceManager
949 ServiceManager.initServiceCache(services);
950 }
951
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800952 setCoreSettings(coreSettings);
953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 AppBindData data = new AppBindData();
955 data.processName = processName;
956 data.appInfo = appInfo;
957 data.providers = providers;
958 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 data.instrumentationArgs = instrumentationArgs;
960 data.instrumentationWatcher = instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800961 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 data.debugMode = debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400963 data.enableBinderTracking = enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700964 data.trackAllocation = trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -0700965 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700966 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400968 data.compatInfo = compatInfo;
Jeff Hao1b012d32014-08-20 10:35:34 -0700969 data.initProfilerInfo = profilerInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700970 data.buildSerial = buildSerial;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800971 data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;
Jeff Brown9ef09972013-10-15 20:49:59 -0700972 sendMessage(H.BIND_APPLICATION, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
974
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400975 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
976 SomeArgs args = SomeArgs.obtain();
977 args.arg1 = entryPoint;
978 args.arg2 = entryPointArgs;
979 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
980 }
981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 public final void scheduleExit() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700983 sendMessage(H.EXIT_APPLICATION, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
985
Christopher Tate5e1ab332009-09-01 20:32:49 -0700986 public final void scheduleSuicide() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700987 sendMessage(H.SUICIDE, null);
Christopher Tate5e1ab332009-09-01 20:32:49 -0700988 }
989
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100990 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
991 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
992 }
993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 public void updateTimeZone() {
995 TimeZone.setDefault(null);
996 }
997
Robert Greenwalt03595d02010-11-02 14:08:23 -0700998 public void clearDnsCache() {
999 // a non-standard API to get this to libcore
1000 InetAddress.clearDnsCache();
Paul Jensene401d172014-09-12 10:47:39 -04001001 // Allow libcore to perform the necessary actions as it sees fit upon a network
1002 // configuration change.
1003 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Robert Greenwalt03595d02010-11-02 14:08:23 -07001004 }
1005
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001006 public void updateHttpProxy() {
Chalard Jean100df0a2018-05-15 23:11:45 +09001007 final ConnectivityManager cm = ConnectivityManager.from(
1008 getApplication() != null ? getApplication() : getSystemContext());
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001009 Proxy.setHttpProxySystemProperty(cm.getDefaultProxy());
Robert Greenwalt434203a2010-10-11 16:00:27 -07001010 }
1011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 public void processInBackground() {
1013 mH.removeMessages(H.GC_WHEN_IDLE);
1014 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1015 }
1016
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001017 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001018 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001019 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001020 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001021 data.token = servicetoken;
1022 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001023 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001024 } catch (IOException e) {
1025 Slog.w(TAG, "dumpService failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001026 } finally {
1027 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 }
1029 }
1030
1031 // This function exists to make sure all receiver dispatching is
1032 // correctly ordered, since these are one-way calls and the binder driver
1033 // applies transaction ordering per object for such calls.
1034 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001035 int resultCode, String dataStr, Bundle extras, boolean ordered,
Dianne Hackborna413dc02013-07-12 12:02:55 -07001036 boolean sticky, int sendingUser, int processState) throws RemoteException {
1037 updateProcessState(processState, false);
Dianne Hackborn20e80982012-08-31 19:00:44 -07001038 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
1039 sticky, sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
Bob Leee5408332009-09-04 18:31:17 -07001041
Wale Ogunwalec2607b42015-02-07 16:16:59 -08001042 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 public void scheduleLowMemory() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001044 sendMessage(H.LOW_MEMORY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046
Wale Ogunwale60454db2015-01-23 16:05:07 -08001047 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -07001048 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
1049 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001050 }
1051
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001052 @Override
Christopher Ferris8d652f82017-04-11 16:29:18 -07001053 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
1054 ParcelFileDescriptor fd) {
Andy McFadden824c5102010-07-09 16:26:57 -07001055 DumpHeapData dhd = new DumpHeapData();
Christopher Ferris8d652f82017-04-11 16:29:18 -07001056 dhd.managed = managed;
1057 dhd.mallocInfo = mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001058 dhd.runGc = runGc;
Andy McFadden824c5102010-07-09 16:26:57 -07001059 dhd.path = path;
1060 dhd.fd = fd;
Christopher Ferris8d652f82017-04-11 16:29:18 -07001061 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
Andy McFadden824c5102010-07-09 16:26:57 -07001062 }
1063
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001064 public void attachAgent(String agent) {
1065 sendMessage(H.ATTACH_AGENT, agent);
1066 }
1067
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001068 public void setSchedulingGroup(int group) {
1069 // Note: do this immediately, since going into the foreground
1070 // should happen regardless of what pending work we have to do
1071 // and the activity manager will wait for us to report back that
1072 // we are done before sending us to the background.
1073 try {
1074 Process.setProcessGroup(Process.myPid(), group);
1075 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001076 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001077 }
1078 }
Bob Leee5408332009-09-04 18:31:17 -07001079
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001080 public void dispatchPackageBroadcast(int cmd, String[] packages) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001081 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001082 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001083
1084 public void scheduleCrash(String msg) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001085 sendMessage(H.SCHEDULE_CRASH, msg);
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001086 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07001087
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001088 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
Dianne Hackborn30d71892010-12-11 10:37:55 -08001089 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001090 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001091 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001092 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001093 data.token = activitytoken;
1094 data.prefix = prefix;
1095 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001096 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001097 } catch (IOException e) {
1098 Slog.w(TAG, "dumpActivity failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001099 } finally {
1100 IoUtils.closeQuietly(pfd);
Dianne Hackborn625ac272010-09-17 18:29:22 -07001101 }
1102 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07001103
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001104 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
Marco Nelissen18cb2872011-11-15 11:19:53 -08001105 String[] args) {
1106 DumpComponentInfo data = new DumpComponentInfo();
1107 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001108 data.fd = pfd.dup();
Marco Nelissen18cb2872011-11-15 11:19:53 -08001109 data.token = providertoken;
1110 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001111 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001112 } catch (IOException e) {
1113 Slog.w(TAG, "dumpProvider failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001114 } finally {
1115 IoUtils.closeQuietly(pfd);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001116 }
1117 }
1118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001120 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001121 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1122 boolean dumpUnreachable, String[] args) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001123 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
Dianne Hackborn8c841092013-06-24 13:46:13 -07001124 PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001125 try {
Colin Crossc4fb5f92016-02-02 16:51:15 -08001126 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001127 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -07001128 pw.flush();
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001129 IoUtils.closeQuietly(pfd);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001130 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001131 }
1132
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001133 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001134 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 long nativeMax = Debug.getNativeHeapSize() / 1024;
1136 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1137 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 Runtime runtime = Runtime.getRuntime();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001140 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 long dalvikMax = runtime.totalMemory() / 1024;
1142 long dalvikFree = runtime.freeMemory() / 1024;
1143 long dalvikAllocated = dalvikMax - dalvikFree;
Richard Uhler2c036192016-09-14 09:48:31 +01001144
1145 Class[] classesToCount = new Class[] {
1146 ContextImpl.class,
1147 Activity.class,
1148 WebView.class,
1149 OpenSSLSocketImpl.class
1150 };
1151 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1152 long appContextInstanceCount = instanceCounts[0];
1153 long activityInstanceCount = instanceCounts[1];
1154 long webviewInstanceCount = instanceCounts[2];
1155 long openSslSocketCount = instanceCounts[3];
1156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -07001158 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 int globalAssetCount = AssetManager.getGlobalAssetCount();
1160 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1161 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1162 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1163 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001164 long parcelSize = Parcel.getGlobalAllocSize();
1165 long parcelCount = Parcel.getGlobalAllocCount();
Vasu Noric3849202010-03-09 10:47:25 -08001166 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -07001167
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07001168 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1169 Process.myPid(),
Dianne Hackborne77187d2013-10-25 16:32:41 -07001170 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1171 nativeMax, nativeAllocated, nativeFree,
1172 dalvikMax, dalvikAllocated, dalvikFree);
1173
Dianne Hackbornb437e092011-08-05 17:50:29 -07001174 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 // NOTE: if you change anything significant below, also consider changing
1176 // ACTIVITY_THREAD_CHECKIN_VERSION.
Anwar Ghuloum3c615062013-05-13 14:18:02 -07001177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 // Object counts
1179 pw.print(viewInstanceCount); pw.print(',');
1180 pw.print(viewRootInstanceCount); pw.print(',');
1181 pw.print(appContextInstanceCount); pw.print(',');
1182 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 pw.print(globalAssetCount); pw.print(',');
1185 pw.print(globalAssetManagerCount); pw.print(',');
1186 pw.print(binderLocalObjectCount); pw.print(',');
1187 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 pw.print(binderDeathObjectCount); pw.print(',');
1190 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 // SQL
Vasu Noric3849202010-03-09 10:47:25 -08001193 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -08001194 pw.print(stats.memoryUsed / 1024); pw.print(',');
1195 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -07001196 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001197 for (int i = 0; i < stats.dbStats.size(); i++) {
1198 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -07001199 pw.print(','); pw.print(dbStats.dbName);
1200 pw.print(','); pw.print(dbStats.pageSize);
1201 pw.print(','); pw.print(dbStats.dbSize);
1202 pw.print(','); pw.print(dbStats.lookaside);
1203 pw.print(','); pw.print(dbStats.cache);
1204 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -08001205 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07001206 pw.println();
Bob Leee5408332009-09-04 18:31:17 -07001207
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001208 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
Bob Leee5408332009-09-04 18:31:17 -07001210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 pw.println(" ");
1212 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001213 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 viewRootInstanceCount);
1215
1216 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1217 "Activities:", activityInstanceCount);
1218
1219 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1220 "AssetManagers:", globalAssetManagerCount);
1221
1222 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1223 "Proxy Binders:", binderProxyObjectCount);
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001224 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1225 "Parcel count:", parcelCount);
1226 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1227 "OpenSSL Sockets:", openSslSocketCount);
Richard Uhler2c036192016-09-14 09:48:31 +01001228 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
Bob Leee5408332009-09-04 18:31:17 -07001229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 // SQLite mem info
1231 pw.println(" ");
1232 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001233 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1234 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1235 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001236 pw.println(" ");
1237 int N = stats.dbStats.size();
1238 if (N > 0) {
1239 pw.println(" DATABASES");
Kweku Adams983829f2017-12-06 14:53:50 -08001240 printRow(pw, DB_INFO_FORMAT, "pgsz", "dbsz", "Lookaside(b)", "cache",
Vasu Nori3c7131f2010-09-21 14:36:57 -07001241 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001242 for (int i = 0; i < N; i++) {
1243 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001244 printRow(pw, DB_INFO_FORMAT,
1245 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1246 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1247 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1248 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001249 }
1250 }
Bob Leee5408332009-09-04 18:31:17 -07001251
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001252 // Asset details.
1253 String assetAlloc = AssetManager.getAssetAllocations();
1254 if (assetAlloc != null) {
1255 pw.println(" ");
1256 pw.println(" Asset Allocations");
1257 pw.print(assetAlloc);
1258 }
Colin Crossc4fb5f92016-02-02 16:51:15 -08001259
1260 // Unreachable native memory
1261 if (dumpUnreachable) {
1262 boolean showContents = ((mBoundApplication != null)
1263 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1264 || android.os.Build.IS_DEBUGGABLE;
1265 pw.println(" ");
1266 pw.println(" Unreachable memory");
1267 pw.print(Debug.getUnreachableMemory(100, showContents));
1268 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001269 }
1270
1271 @Override
Kweku Adams983829f2017-12-06 14:53:50 -08001272 public void dumpMemInfoProto(ParcelFileDescriptor pfd, Debug.MemoryInfo mem,
1273 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1274 boolean dumpUnreachable, String[] args) {
1275 ProtoOutputStream proto = new ProtoOutputStream(pfd.getFileDescriptor());
1276 try {
1277 dumpMemInfo(proto, mem, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1278 } finally {
1279 proto.flush();
1280 IoUtils.closeQuietly(pfd);
1281 }
1282 }
1283
1284 private void dumpMemInfo(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
1285 boolean dumpFullInfo, boolean dumpDalvik,
1286 boolean dumpSummaryOnly, boolean dumpUnreachable) {
1287 long nativeMax = Debug.getNativeHeapSize() / 1024;
1288 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1289 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1290
1291 Runtime runtime = Runtime.getRuntime();
1292 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1293 long dalvikMax = runtime.totalMemory() / 1024;
1294 long dalvikFree = runtime.freeMemory() / 1024;
1295 long dalvikAllocated = dalvikMax - dalvikFree;
1296
1297 Class[] classesToCount = new Class[] {
1298 ContextImpl.class,
1299 Activity.class,
1300 WebView.class,
1301 OpenSSLSocketImpl.class
1302 };
1303 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1304 long appContextInstanceCount = instanceCounts[0];
1305 long activityInstanceCount = instanceCounts[1];
1306 long webviewInstanceCount = instanceCounts[2];
1307 long openSslSocketCount = instanceCounts[3];
1308
1309 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1310 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1311 int globalAssetCount = AssetManager.getGlobalAssetCount();
1312 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1313 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1314 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1315 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1316 long parcelSize = Parcel.getGlobalAllocSize();
1317 long parcelCount = Parcel.getGlobalAllocCount();
1318 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1319
Yi Jin2b30f322018-02-20 15:41:47 -08001320 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
1321 proto.write(MemInfoDumpProto.ProcessMemory.PID, Process.myPid());
1322 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME,
Kweku Adams983829f2017-12-06 14:53:50 -08001323 (mBoundApplication != null) ? mBoundApplication.processName : "unknown");
1324 dumpMemInfoTable(proto, memInfo, dumpDalvik, dumpSummaryOnly,
1325 nativeMax, nativeAllocated, nativeFree,
1326 dalvikMax, dalvikAllocated, dalvikFree);
1327 proto.end(mToken);
1328
Yi Jin2b30f322018-02-20 15:41:47 -08001329 final long oToken = proto.start(MemInfoDumpProto.AppData.OBJECTS);
1330 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_INSTANCE_COUNT,
1331 viewInstanceCount);
1332 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_ROOT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001333 viewRootInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001334 proto.write(MemInfoDumpProto.AppData.ObjectStats.APP_CONTEXT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001335 appContextInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001336 proto.write(MemInfoDumpProto.AppData.ObjectStats.ACTIVITY_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001337 activityInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001338 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_COUNT,
1339 globalAssetCount);
1340 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_MANAGER_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001341 globalAssetManagerCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001342 proto.write(MemInfoDumpProto.AppData.ObjectStats.LOCAL_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001343 binderLocalObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001344 proto.write(MemInfoDumpProto.AppData.ObjectStats.PROXY_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001345 binderProxyObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001346 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_MEMORY_KB,
1347 parcelSize / 1024);
1348 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_COUNT, parcelCount);
1349 proto.write(MemInfoDumpProto.AppData.ObjectStats.BINDER_OBJECT_DEATH_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001350 binderDeathObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001351 proto.write(MemInfoDumpProto.AppData.ObjectStats.OPEN_SSL_SOCKET_COUNT,
1352 openSslSocketCount);
1353 proto.write(MemInfoDumpProto.AppData.ObjectStats.WEBVIEW_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001354 webviewInstanceCount);
1355 proto.end(oToken);
1356
1357 // SQLite mem info
Yi Jin2b30f322018-02-20 15:41:47 -08001358 final long sToken = proto.start(MemInfoDumpProto.AppData.SQL);
1359 proto.write(MemInfoDumpProto.AppData.SqlStats.MEMORY_USED_KB,
1360 stats.memoryUsed / 1024);
1361 proto.write(MemInfoDumpProto.AppData.SqlStats.PAGECACHE_OVERFLOW_KB,
Kweku Adams983829f2017-12-06 14:53:50 -08001362 stats.pageCacheOverflow / 1024);
Yi Jin2b30f322018-02-20 15:41:47 -08001363 proto.write(MemInfoDumpProto.AppData.SqlStats.MALLOC_SIZE_KB,
1364 stats.largestMemAlloc / 1024);
Kweku Adams983829f2017-12-06 14:53:50 -08001365 int n = stats.dbStats.size();
1366 for (int i = 0; i < n; i++) {
1367 DbStats dbStats = stats.dbStats.get(i);
1368
Yi Jin2b30f322018-02-20 15:41:47 -08001369 final long dToken = proto.start(MemInfoDumpProto.AppData.SqlStats.DATABASES);
1370 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.NAME, dbStats.dbName);
1371 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.PAGE_SIZE, dbStats.pageSize);
1372 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.DB_SIZE, dbStats.dbSize);
1373 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.LOOKASIDE_B,
1374 dbStats.lookaside);
1375 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.CACHE, dbStats.cache);
Kweku Adams983829f2017-12-06 14:53:50 -08001376 proto.end(dToken);
1377 }
1378 proto.end(sToken);
1379
1380 // Asset details.
1381 String assetAlloc = AssetManager.getAssetAllocations();
1382 if (assetAlloc != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08001383 proto.write(MemInfoDumpProto.AppData.ASSET_ALLOCATIONS, assetAlloc);
Kweku Adams983829f2017-12-06 14:53:50 -08001384 }
1385
1386 // Unreachable native memory
1387 if (dumpUnreachable) {
1388 int flags = mBoundApplication == null ? 0 : mBoundApplication.appInfo.flags;
1389 boolean showContents = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
1390 || android.os.Build.IS_DEBUGGABLE;
Yi Jin2b30f322018-02-20 15:41:47 -08001391 proto.write(MemInfoDumpProto.AppData.UNREACHABLE_MEMORY,
Kweku Adams983829f2017-12-06 14:53:50 -08001392 Debug.getUnreachableMemory(100, showContents));
1393 }
1394 }
1395
1396 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001397 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
Chris Craikfc294242016-12-13 18:10:46 -08001398 nDumpGraphicsInfo(pfd.getFileDescriptor());
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001399 WindowManagerGlobal.getInstance().dumpGfxInfo(pfd.getFileDescriptor(), args);
1400 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001403 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args) {
1404 PrintWriter pw = new FastPrintWriter(
1405 new FileOutputStream(pfd.getFileDescriptor()));
Jeff Brown6754ba22011-12-14 20:20:01 -08001406 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1407 SQLiteDebug.dump(printer, args);
1408 pw.flush();
1409 }
1410
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001411 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001412 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001413 if (mSystemThread) {
Felipe Leme29de4922016-06-07 16:14:07 -07001414 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1415 // be consumed. But it must duplicate the file descriptor first, since caller might
1416 // be closing it.
1417 final ParcelFileDescriptor dup;
1418 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001419 dup = pfd.dup();
Felipe Leme29de4922016-06-07 16:14:07 -07001420 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001421 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
Felipe Leme29de4922016-06-07 16:14:07 -07001422 return;
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001423 } finally {
1424 IoUtils.closeQuietly(pfd);
Felipe Leme29de4922016-06-07 16:14:07 -07001425 }
1426
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001427 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1428 @Override
1429 public void run() {
Felipe Lemec74972f2016-06-08 09:12:37 -07001430 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001431 dumpDatabaseInfo(dup, args);
Felipe Lemec74972f2016-06-08 09:12:37 -07001432 } finally {
1433 IoUtils.closeQuietly(dup);
1434 }
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001435 }
1436 });
1437 } else {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001438 dumpDatabaseInfo(pfd, args);
1439 IoUtils.closeQuietly(pfd);
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001440 }
1441 }
1442
1443 @Override
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001444 public void unstableProviderDied(IBinder provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001445 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001446 }
1447
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001448 @Override
Adam Skorydfc7fd72013-08-05 19:23:41 -07001449 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
Svet Ganovfd31f852017-04-26 15:54:27 -07001450 int requestType, int sessionId, int flags) {
Adam Skorydfc7fd72013-08-05 19:23:41 -07001451 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001452 cmd.activityToken = activityToken;
1453 cmd.requestToken = requestToken;
1454 cmd.requestType = requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -07001455 cmd.sessionId = sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -07001456 cmd.flags = flags;
Jeff Brown9ef09972013-10-15 20:49:59 -07001457 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001458 }
1459
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001460 public void setCoreSettings(Bundle coreSettings) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001461 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001462 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001463
1464 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1465 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1466 ucd.pkg = pkg;
1467 ucd.info = info;
Jeff Brown9ef09972013-10-15 20:49:59 -07001468 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001469 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001470
1471 public void scheduleTrimMemory(int level) {
Jorim Jaggib29e3182018-04-30 18:51:56 +02001472 final Runnable r = PooledLambda.obtainRunnable(ActivityThread::handleTrimMemory,
1473 ActivityThread.this, level);
1474 // Schedule trimming memory after drawing the frame to minimize jank-risk.
1475 Choreographer choreographer = Choreographer.getMainThreadInstance();
1476 if (choreographer != null) {
1477 choreographer.postCallback(Choreographer.CALLBACK_COMMIT, r, null);
1478 } else {
1479 mH.post(r);
1480 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001481 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001482
Craig Mautner5eda9b32013-07-02 11:58:16 -07001483 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001484 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001485 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001486
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001487 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
Craig Mautnereb8abf72014-07-02 15:04:09 -07001488 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001489 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
Craig Mautnereb8abf72014-07-02 15:04:09 -07001490 }
1491
Dianne Hackborna413dc02013-07-12 12:02:55 -07001492 public void setProcessState(int state) {
1493 updateProcessState(state, true);
1494 }
1495
1496 public void updateProcessState(int processState, boolean fromIpc) {
1497 synchronized (this) {
1498 if (mLastProcessState != processState) {
1499 mLastProcessState = processState;
Mathieu Chartier1e370902013-07-18 10:58:01 -07001500 // Update Dalvik state based on ActivityManager.PROCESS_STATE_* constants.
1501 final int DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
1502 final int DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
1503 int dalvikProcessState = DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE;
1504 // TODO: Tune this since things like gmail sync are important background but not jank perceptible.
1505 if (processState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
1506 dalvikProcessState = DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE;
1507 }
1508 VMRuntime.getRuntime().updateProcessState(dalvikProcessState);
Dianne Hackborna413dc02013-07-12 12:02:55 -07001509 if (false) {
1510 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
1511 + (fromIpc ? " (from ipc": ""));
1512 }
1513 }
1514 }
1515 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001516
Sudheer Shanka84a48952017-03-08 18:19:01 -08001517 /**
1518 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1519 * the main thread that it needs to wait for the network rules to get updated before
1520 * launching an activity.
1521 */
1522 @Override
1523 public void setNetworkBlockSeq(long procStateSeq) {
1524 synchronized (mNetworkPolicyLock) {
1525 mNetworkBlockSeq = procStateSeq;
1526 }
1527 }
1528
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001529 @Override
1530 public void scheduleInstallProvider(ProviderInfo provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001531 sendMessage(H.INSTALL_PROVIDER, provider);
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001532 }
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001533
1534 @Override
Neil Fullerb7146fe2016-11-15 16:52:15 +00001535 public final void updateTimePrefs(int timeFormatPreference) {
1536 final Boolean timeFormatPreferenceBool;
1537 // For convenience we are using the Intent extra values.
1538 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1539 timeFormatPreferenceBool = Boolean.FALSE;
1540 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1541 timeFormatPreferenceBool = Boolean.TRUE;
1542 } else {
1543 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1544 // (or unknown).
1545 timeFormatPreferenceBool = null;
1546 }
1547 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001548 }
Craig Mautneree2e45a2014-06-27 12:10:03 -07001549
1550 @Override
Craig Mautner8746a472014-07-24 15:12:54 -07001551 public void scheduleEnterAnimationComplete(IBinder token) {
1552 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1553 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001554
1555 @Override
1556 public void notifyCleartextNetwork(byte[] firstPacket) {
1557 if (StrictMode.vmCleartextNetworkEnabled()) {
1558 StrictMode.onCleartextNetworkDetected(firstPacket);
1559 }
1560 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001561
1562 @Override
1563 public void startBinderTracking() {
1564 sendMessage(H.START_BINDER_TRACKING, null);
1565 }
1566
1567 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001568 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001569 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001570 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001571 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001572 } finally {
1573 IoUtils.closeQuietly(pfd);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001574 }
1575 }
Wale Ogunwale5f986092015-12-04 15:35:38 -08001576
1577 @Override
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001578 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1579 IVoiceInteractor voiceInteractor) throws RemoteException {
1580 SomeArgs args = SomeArgs.obtain();
1581 args.arg1 = token;
1582 args.arg2 = voiceInteractor;
1583 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1584 }
Chad Brubakerc72875b2016-04-27 16:35:11 -07001585
1586 @Override
1587 public void handleTrustStorageUpdate() {
1588 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1589 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001590
1591 @Override
1592 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1593 ActivityThread.this.scheduleTransaction(transaction);
1594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 }
1596
Andrii Kulian446e8242017-10-26 15:17:29 -07001597 @Override
1598 public void updatePendingConfiguration(Configuration config) {
1599 mAppThread.updatePendingConfiguration(config);
1600 }
1601
1602 @Override
1603 public void updateProcessState(int processState, boolean fromIpc) {
1604 mAppThread.updateProcessState(processState, fromIpc);
1605 }
1606
Andrii Kulian446e8242017-10-26 15:17:29 -07001607 class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 public static final int BIND_APPLICATION = 110;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001609 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 public static final int EXIT_APPLICATION = 111;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001611 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 public static final int RECEIVER = 113;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001613 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 public static final int CREATE_SERVICE = 114;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001615 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 public static final int SERVICE_ARGS = 115;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001617 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 public static final int STOP_SERVICE = 116;
Dianne Hackborn09233282014-04-30 11:33:59 -07001619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 public static final int CONFIGURATION_CHANGED = 118;
1621 public static final int CLEAN_UP_CONTEXT = 119;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001622 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 public static final int GC_WHEN_IDLE = 120;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001624 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 public static final int BIND_SERVICE = 121;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001626 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 public static final int UNBIND_SERVICE = 122;
1628 public static final int DUMP_SERVICE = 123;
1629 public static final int LOW_MEMORY = 124;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001630 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001631 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001632 public static final int DESTROY_BACKUP_AGENT = 129;
1633 public static final int SUICIDE = 130;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001634 @UnsupportedAppUsage
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001635 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001636 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001637 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001638 @UnsupportedAppUsage
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001639 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001640 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001641 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001642 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001643 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001644 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001645 @UnsupportedAppUsage
Marco Nelissen18cb2872011-11-15 11:19:53 -08001646 public static final int DUMP_PROVIDER = 141;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001647 public static final int UNSTABLE_PROVIDER_DIED = 142;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001648 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001649 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001650 @UnsupportedAppUsage
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001651 public static final int INSTALL_PROVIDER = 145;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001652 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001653 @UnsupportedAppUsage
Craig Mautner8746a472014-07-24 15:12:54 -07001654 public static final int ENTER_ANIMATION_COMPLETE = 149;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001655 public static final int START_BINDER_TRACKING = 150;
1656 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001657 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001658 public static final int ATTACH_AGENT = 155;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001659 public static final int APPLICATION_INFO_CHANGED = 156;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001660 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
Andrii Kulian446e8242017-10-26 15:17:29 -07001661 public static final int EXECUTE_TRANSACTION = 159;
Andrii Kulian320e3b52018-05-03 16:26:25 -07001662 public static final int RELAUNCH_ACTIVITY = 160;
Tim Murray12f511e2018-10-22 15:26:08 -07001663 public static final int PURGE_RESOURCES = 161;
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001666 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 switch (code) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 case BIND_APPLICATION: return "BIND_APPLICATION";
1669 case EXIT_APPLICATION: return "EXIT_APPLICATION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 case RECEIVER: return "RECEIVER";
1671 case CREATE_SERVICE: return "CREATE_SERVICE";
1672 case SERVICE_ARGS: return "SERVICE_ARGS";
1673 case STOP_SERVICE: return "STOP_SERVICE";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1675 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1676 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1677 case BIND_SERVICE: return "BIND_SERVICE";
1678 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1679 case DUMP_SERVICE: return "DUMP_SERVICE";
1680 case LOW_MEMORY: return "LOW_MEMORY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001681 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001682 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1683 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001684 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001685 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001686 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001687 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001688 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001689 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001690 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001691 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001692 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001693 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001694 case DUMP_PROVIDER: return "DUMP_PROVIDER";
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001695 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
Adam Skorydfc7fd72013-08-05 19:23:41 -07001696 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
Craig Mautner5eda9b32013-07-02 11:58:16 -07001697 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001698 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
Craig Mautnereb8abf72014-07-02 15:04:09 -07001699 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
Craig Mautner8746a472014-07-24 15:12:54 -07001700 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001701 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001702 case ATTACH_AGENT: return "ATTACH_AGENT";
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001703 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001704 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
Andrii Kulian446e8242017-10-26 15:17:29 -07001705 case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
Andrii Kulian320e3b52018-05-03 16:26:25 -07001706 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
Tim Murray12f511e2018-10-22 15:26:08 -07001707 case PURGE_RESOURCES: return "PURGE_RESOURCES";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
1709 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001710 return Integer.toString(code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
1712 public void handleMessage(Message msg) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001713 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 case BIND_APPLICATION:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001716 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 AppBindData data = (AppBindData)msg.obj;
1718 handleBindApplication(data);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001719 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 break;
1721 case EXIT_APPLICATION:
1722 if (mInitialApplication != null) {
1723 mInitialApplication.onTerminate();
1724 }
1725 Looper.myLooper().quit();
1726 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 case RECEIVER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001728 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 handleReceiver((ReceiverData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001730 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 break;
1732 case CREATE_SERVICE:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001733 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 handleCreateService((CreateServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001735 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 break;
1737 case BIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001738 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 handleBindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001740 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 break;
1742 case UNBIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001743 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 handleUnbindService((BindServiceData)msg.obj);
Tim Murray12f511e2018-10-22 15:26:08 -07001745 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001746 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 break;
1748 case SERVICE_ARGS:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001749 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceStart: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 handleServiceArgs((ServiceArgsData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001751 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 break;
1753 case STOP_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001754 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 handleStopService((IBinder)msg.obj);
Tim Murray12f511e2018-10-22 15:26:08 -07001756 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001757 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 case CONFIGURATION_CHANGED:
Andrii Kulian446e8242017-10-26 15:17:29 -07001760 handleConfigurationChanged((Configuration) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 break;
1762 case CLEAN_UP_CONTEXT:
1763 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1764 cci.context.performFinalCleanup(cci.who, cci.what);
1765 break;
1766 case GC_WHEN_IDLE:
1767 scheduleGcIdler();
1768 break;
1769 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001770 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 break;
1772 case LOW_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001773 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 handleLowMemory();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001775 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001777 case PROFILER_CONTROL:
Jeff Hao1b012d32014-08-20 10:35:34 -07001778 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001779 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001780 case CREATE_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001781 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001782 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001783 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001784 break;
1785 case DESTROY_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001786 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001787 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001788 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001789 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001790 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001791 Process.killProcess(Process.myPid());
1792 break;
1793 case REMOVE_PROVIDER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001794 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001795 completeRemoveProvider((ProviderRefCount)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001796 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001797 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001798 case ENABLE_JIT:
1799 ensureJitEnabled();
1800 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001801 case DISPATCH_PACKAGE_BROADCAST:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001802 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001803 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001804 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001805 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001806 case SCHEDULE_CRASH:
1807 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001808 case DUMP_HEAP:
Christopher Ferris8d652f82017-04-11 16:29:18 -07001809 handleDumpHeap((DumpHeapData) msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001810 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001811 case DUMP_ACTIVITY:
1812 handleDumpActivity((DumpComponentInfo)msg.obj);
1813 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001814 case DUMP_PROVIDER:
1815 handleDumpProvider((DumpComponentInfo)msg.obj);
1816 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001817 case SLEEPING:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001818 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001819 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001820 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001821 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001822 case SET_CORE_SETTINGS:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001823 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001824 handleSetCoreSettings((Bundle) msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001825 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001826 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001827 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1828 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001829 break;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001830 case UNSTABLE_PROVIDER_DIED:
1831 handleUnstableProviderDied((IBinder)msg.obj, false);
1832 break;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001833 case REQUEST_ASSIST_CONTEXT_EXTRAS:
1834 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001835 break;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001836 case TRANSLUCENT_CONVERSION_COMPLETE:
1837 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
1838 break;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001839 case INSTALL_PROVIDER:
1840 handleInstallProvider((ProviderInfo) msg.obj);
1841 break;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001842 case ON_NEW_ACTIVITY_OPTIONS:
1843 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
1844 onNewActivityOptions(pair.first, pair.second);
Dake Gu7ef70b02014-07-08 18:37:12 -07001845 break;
Craig Mautner8746a472014-07-24 15:12:54 -07001846 case ENTER_ANIMATION_COMPLETE:
1847 handleEnterAnimationComplete((IBinder) msg.obj);
1848 break;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001849 case START_BINDER_TRACKING:
1850 handleStartBinderTracking();
1851 break;
1852 case STOP_BINDER_TRACKING_AND_DUMP:
1853 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
1854 break;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001855 case LOCAL_VOICE_INTERACTION_STARTED:
1856 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
1857 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
Amith Yamasani61019112017-01-10 15:05:00 -08001858 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001859 case ATTACH_AGENT: {
1860 Application app = getApplication();
1861 handleAttachAgent((String) msg.obj, app != null ? app.mLoadedApk : null);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001862 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001863 }
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001864 case APPLICATION_INFO_CHANGED:
1865 mUpdatingSystemConfig = true;
1866 try {
1867 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
1868 } finally {
1869 mUpdatingSystemConfig = false;
1870 }
1871 break;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001872 case RUN_ISOLATED_ENTRY_POINT:
1873 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
1874 (String[]) ((SomeArgs) msg.obj).arg2);
1875 break;
Andrii Kulian446e8242017-10-26 15:17:29 -07001876 case EXECUTE_TRANSACTION:
Andrii Kulian04470682018-01-10 15:32:31 -08001877 final ClientTransaction transaction = (ClientTransaction) msg.obj;
1878 mTransactionExecutor.execute(transaction);
1879 if (isSystem()) {
1880 // Client transactions inside system process are recycled on the client side
1881 // instead of ClientLifecycleManager to avoid being cleared before this
1882 // message is handled.
1883 transaction.recycle();
1884 }
Andrii Kulian914aa7d2018-03-19 21:51:53 -07001885 // TODO(lifecycler): Recycle locally scheduled transactions.
Andrii Kulian446e8242017-10-26 15:17:29 -07001886 break;
Andrii Kulian320e3b52018-05-03 16:26:25 -07001887 case RELAUNCH_ACTIVITY:
1888 handleRelaunchActivityLocally((IBinder) msg.obj);
1889 break;
Tim Murray12f511e2018-10-22 15:26:08 -07001890 case PURGE_RESOURCES:
1891 schedulePurgeIdler();
1892 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001894 Object obj = msg.obj;
1895 if (obj instanceof SomeArgs) {
1896 ((SomeArgs) obj).recycle();
1897 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001898 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
1900 }
1901
Romain Guy65b345f2011-07-27 18:51:50 -07001902 private class Idler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001903 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001905 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001906 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001907 if (mBoundApplication != null && mProfiler.profileFd != null
1908 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001909 stopProfiling = true;
1910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 if (a != null) {
1912 mNewActivities = null;
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001913 IActivityManager am = ActivityManager.getService();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001914 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001916 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 TAG, "Reporting idle of " + a +
1918 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001919 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 if (a.activity != null && !a.activity.mFinished) {
1921 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001922 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001923 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001925 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 }
1927 }
1928 prev = a;
1929 a = a.nextIdle;
1930 prev.nextIdle = null;
1931 } while (a != null);
1932 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001933 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001934 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001935 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001936 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 return false;
1938 }
1939 }
1940
1941 final class GcIdler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001942 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 public final boolean queueIdle() {
1944 doGcIfNeeded();
Tim Murray12f511e2018-10-22 15:26:08 -07001945 nPurgePendingResources();
1946 return false;
1947 }
1948 }
1949
1950 final class PurgeIdler implements MessageQueue.IdleHandler {
1951 @Override
1952 public boolean queueIdle() {
1953 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "purgePendingResources");
1954 nPurgePendingResources();
1955 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 return false;
1957 }
1958 }
1959
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001960 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07001961 public static ActivityThread currentActivityThread() {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08001962 return sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964
Wale Ogunwale9a6ef1e2015-06-02 13:41:00 -07001965 public static boolean isSystem() {
1966 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
1967 }
1968
Svetoslavfbf0eca2015-05-01 16:52:41 -07001969 public static String currentOpPackageName() {
1970 ActivityThread am = currentActivityThread();
1971 return (am != null && am.getApplication() != null)
1972 ? am.getApplication().getOpPackageName() : null;
1973 }
1974
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001975 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07001976 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001977 ActivityThread am = currentActivityThread();
1978 return (am != null && am.mBoundApplication != null)
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07001979 ? am.mBoundApplication.appInfo.packageName : null;
1980 }
1981
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001982 @UnsupportedAppUsage
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07001983 public static String currentProcessName() {
1984 ActivityThread am = currentActivityThread();
1985 return (am != null && am.mBoundApplication != null)
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001986 ? am.mBoundApplication.processName : null;
1987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001989 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07001990 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001991 ActivityThread am = currentActivityThread();
1992 return am != null ? am.mInitialApplication : null;
1993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994
Mathew Inwood4fb17d12018-08-14 14:25:44 +01001995 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001996 public static IPackageManager getPackageManager() {
1997 if (sPackageManager != null) {
1998 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1999 return sPackageManager;
2000 }
2001 IBinder b = ServiceManager.getService("package");
2002 //Slog.v("PackageManager", "default service binder = " + b);
2003 sPackageManager = IPackageManager.Stub.asInterface(b);
2004 //Slog.v("PackageManager", "default service = " + sPackageManager);
2005 return sPackageManager;
2006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007
Romain Guy65b345f2011-07-27 18:51:50 -07002008 private Configuration mMainThreadConfig = new Configuration();
Amith Yamasani4f128e42016-05-10 11:44:12 -07002009
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002010 Configuration applyConfigCompatMainThread(int displayDensity, Configuration config,
2011 CompatibilityInfo compat) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002012 if (config == null) {
2013 return null;
2014 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002015 if (!compat.supportsScreen()) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002016 mMainThreadConfig.setTo(config);
2017 config = mMainThreadConfig;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002018 compat.applyToConfiguration(displayDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002019 }
2020 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002023 /**
Todd Kennedy39bfee52016-02-24 10:28:21 -08002024 * Creates the top level resources for the given package. Will return an existing
2025 * Resources if one has already been created.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002026 */
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07002027 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
Adam Lesinski082614c2016-03-04 14:33:47 -08002028 String[] libDirs, int displayId, LoadedApk pkgInfo) {
2029 return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,
2030 displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader());
Todd Kennedy39bfee52016-02-24 10:28:21 -08002031 }
2032
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002033 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002034 final Handler getHandler() {
2035 return mH;
2036 }
2037
Mathew Inwood45d2c252018-09-14 12:35:36 +01002038 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002039 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2040 int flags) {
2041 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
Amith Yamasani98edc952012-09-25 14:09:27 -07002042 }
2043
Todd Kennedy233a0b12018-01-29 20:30:24 +00002044 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2045 int flags, int userId) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002046 final boolean differentUser = (UserHandle.myUserId() != userId);
Craig Mautner88c05892013-06-28 09:47:45 -07002047 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002048 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002049 if (differentUser) {
2050 // Caching not supported across users
2051 ref = null;
2052 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 ref = mPackages.get(packageName);
2054 } else {
2055 ref = mResourcePackages.get(packageName);
2056 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002057
Todd Kennedy233a0b12018-01-29 20:30:24 +00002058 LoadedApk packageInfo = ref != null ? ref.get() : null;
2059 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
2060 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
2061 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
2062 if (packageInfo != null && (packageInfo.mResources == null
2063 || packageInfo.mResources.getAssets().isUpToDate())) {
2064 if (packageInfo.isSecurityViolation()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2066 throw new SecurityException(
2067 "Requesting code from " + packageName
2068 + " to be run in process "
2069 + mBoundApplication.processName
2070 + "/" + mBoundApplication.appInfo.uid);
2071 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002072 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 }
2074 }
2075
2076 ApplicationInfo ai = null;
2077 try {
2078 ai = getPackageManager().getApplicationInfo(packageName,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002079 PackageManager.GET_SHARED_LIBRARY_FILES
2080 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2081 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002083 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085
2086 if (ai != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002087 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089
2090 return null;
2091 }
2092
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002093 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002094 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002095 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2097 boolean securityViolation = includeCode && ai.uid != 0
2098 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002099 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
Amith Yamasani742a6712011-05-04 14:49:28 -07002100 : true);
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002101 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2103 |Context.CONTEXT_IGNORE_SECURITY))
2104 == Context.CONTEXT_INCLUDE_CODE) {
2105 if (securityViolation) {
2106 String msg = "Requesting code from " + ai.packageName
2107 + " (with uid " + ai.uid + ")";
2108 if (mBoundApplication != null) {
2109 msg = msg + " to be run in process "
2110 + mBoundApplication.processName + " (with uid "
2111 + mBoundApplication.appInfo.uid + ")";
2112 }
2113 throw new SecurityException(msg);
2114 }
2115 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002116 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002117 registerPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
2119
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002120 @Override
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002121 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002122 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002123 CompatibilityInfo compatInfo) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002124 return getPackageInfo(ai, compatInfo, null, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 }
2126
Mathew Inwood45d2c252018-09-14 12:35:36 +01002127 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002128 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
Craig Mautner88c05892013-06-28 09:47:45 -07002129 synchronized (mResourcesManager) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002130 WeakReference<LoadedApk> ref;
2131 if (includeCode) {
2132 ref = mPackages.get(packageName);
2133 } else {
2134 ref = mResourcePackages.get(packageName);
2135 }
2136 return ref != null ? ref.get() : null;
2137 }
2138 }
2139
Todd Kennedy233a0b12018-01-29 20:30:24 +00002140 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002141 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2142 boolean registerPackage) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002143 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
Craig Mautner88c05892013-06-28 09:47:45 -07002144 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002145 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002146 if (differentUser) {
2147 // Caching not supported across users
2148 ref = null;
2149 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 ref = mPackages.get(aInfo.packageName);
2151 } else {
2152 ref = mResourcePackages.get(aInfo.packageName);
2153 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002154
Todd Kennedy233a0b12018-01-29 20:30:24 +00002155 LoadedApk packageInfo = ref != null ? ref.get() : null;
2156 if (packageInfo == null || (packageInfo.mResources != null
2157 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002158 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 : "Loading resource-only package ") + aInfo.packageName
2160 + " (in " + (mBoundApplication != null
2161 ? mBoundApplication.processName : null)
2162 + ")");
Todd Kennedy233a0b12018-01-29 20:30:24 +00002163 packageInfo =
Jeff Browndefd4a62014-03-10 21:24:37 -07002164 new LoadedApk(this, aInfo, compatInfo, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 securityViolation, includeCode &&
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002166 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
Narayan Kamathcb383182014-10-29 17:56:42 +00002167
2168 if (mSystemThread && "android".equals(aInfo.packageName)) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002169 packageInfo.installSystemApplicationInfo(aInfo,
2170 getSystemContext().mPackageInfo.getClassLoader());
Narayan Kamathcb383182014-10-29 17:56:42 +00002171 }
2172
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002173 if (differentUser) {
2174 // Caching not supported across users
2175 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 mPackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002177 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 } else {
2179 mResourcePackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002180 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 }
2182 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002183 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 }
2185 }
2186
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002187 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 ActivityThread() {
Craig Mautner88c05892013-06-28 09:47:45 -07002189 mResourcesManager = ResourcesManager.getInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 }
2191
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002192 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 public ApplicationThread getApplicationThread()
2194 {
2195 return mAppThread;
2196 }
2197
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002198 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 public Instrumentation getInstrumentation()
2200 {
2201 return mInstrumentation;
2202 }
2203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002205 return mProfiler != null && mProfiler.profileFile != null
2206 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 }
2208
2209 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002210 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 }
2212
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002213 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 public Looper getLooper() {
2215 return mLooper;
2216 }
2217
Jeff Sharkey8439ac02017-12-12 17:26:23 -07002218 public Executor getExecutor() {
2219 return mExecutor;
2220 }
2221
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002222 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 public Application getApplication() {
2224 return mInitialApplication;
2225 }
Bob Leee5408332009-09-04 18:31:17 -07002226
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002227 @UnsupportedAppUsage
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002228 public String getProcessName() {
2229 return mBoundApplication.processName;
2230 }
Bob Leee5408332009-09-04 18:31:17 -07002231
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002232 @UnsupportedAppUsage
Dianne Hackborn21556372010-02-04 16:34:40 -08002233 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 synchronized (this) {
2235 if (mSystemContext == null) {
Jeff Browndefd4a62014-03-10 21:24:37 -07002236 mSystemContext = ContextImpl.createSystemContext(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 }
Jeff Browndefd4a62014-03-10 21:24:37 -07002238 return mSystemContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 }
2241
Adam Lesinskia82b6262017-03-21 16:56:17 -07002242 public ContextImpl getSystemUiContext() {
2243 synchronized (this) {
2244 if (mSystemUiContext == null) {
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002245 mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
Adam Lesinskia82b6262017-03-21 16:56:17 -07002246 }
2247 return mSystemUiContext;
2248 }
2249 }
2250
Narayan Kamath29564cd2014-08-07 10:57:40 +01002251 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Mike Cleron432b7132009-09-24 15:28:29 -07002252 synchronized (this) {
Narayan Kamath29564cd2014-08-07 10:57:40 +01002253 getSystemContext().installSystemApplicationInfo(info, classLoader);
Adam Lesinskia82b6262017-03-21 16:56:17 -07002254 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002255
2256 // give ourselves a default profiler
2257 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07002258 }
2259 }
2260
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002261 void ensureJitEnabled() {
2262 if (!mJitEnabled) {
2263 mJitEnabled = true;
2264 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
2265 }
2266 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002267
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002268 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 void scheduleGcIdler() {
2270 if (!mGcIdlerScheduled) {
2271 mGcIdlerScheduled = true;
2272 Looper.myQueue().addIdleHandler(mGcIdler);
2273 }
2274 mH.removeMessages(H.GC_WHEN_IDLE);
2275 }
2276
2277 void unscheduleGcIdler() {
2278 if (mGcIdlerScheduled) {
2279 mGcIdlerScheduled = false;
2280 Looper.myQueue().removeIdleHandler(mGcIdler);
2281 }
2282 mH.removeMessages(H.GC_WHEN_IDLE);
2283 }
2284
Tim Murray12f511e2018-10-22 15:26:08 -07002285 void schedulePurgeIdler() {
2286 if (!mPurgeIdlerScheduled) {
2287 mPurgeIdlerScheduled = true;
2288 Looper.myQueue().addIdleHandler(mPurgeIdler);
2289 }
2290 mH.removeMessages(H.PURGE_RESOURCES);
2291 }
2292
2293 void unschedulePurgeIdler() {
2294 if (mPurgeIdlerScheduled) {
2295 mPurgeIdlerScheduled = false;
2296 Looper.myQueue().removeIdleHandler(mPurgeIdler);
2297 }
2298 mH.removeMessages(H.PURGE_RESOURCES);
2299 }
2300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 void doGcIfNeeded() {
2302 mGcIdlerScheduled = false;
2303 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002304 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 // + "m now=" + now);
2306 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002307 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 BinderInternal.forceGc("bg");
2309 }
2310 }
2311
Dianne Hackborne77187d2013-10-25 16:32:41 -07002312 private static final String HEAP_FULL_COLUMN
2313 = "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2314 private static final String HEAP_COLUMN
2315 = "%13s %8s %8s %8s %8s %8s %8s %8s";
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002316 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2317 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
2318 private static final String ONE_COUNT_COLUMN_HEADER = "%21s %8s";
Dianne Hackborne77187d2013-10-25 16:32:41 -07002319
2320 // Formatting for checkin service - update version if row format changes
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002321 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002322
2323 static void printRow(PrintWriter pw, String format, Object...objs) {
2324 pw.println(String.format(format, objs));
2325 }
2326
2327 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002328 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2329 int pid, String processName,
Dianne Hackborne77187d2013-10-25 16:32:41 -07002330 long nativeMax, long nativeAllocated, long nativeFree,
2331 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2332
2333 // For checkin, we print one long comma-separated list of values
2334 if (checkin) {
2335 // NOTE: if you change anything significant below, also consider changing
2336 // ACTIVITY_THREAD_CHECKIN_VERSION.
2337
2338 // Header
2339 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2340 pw.print(pid); pw.print(',');
2341 pw.print(processName); pw.print(',');
2342
2343 // Heap info - max
2344 pw.print(nativeMax); pw.print(',');
2345 pw.print(dalvikMax); pw.print(',');
2346 pw.print("N/A,");
2347 pw.print(nativeMax + dalvikMax); pw.print(',');
2348
2349 // Heap info - allocated
2350 pw.print(nativeAllocated); pw.print(',');
2351 pw.print(dalvikAllocated); pw.print(',');
2352 pw.print("N/A,");
2353 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2354
2355 // Heap info - free
2356 pw.print(nativeFree); pw.print(',');
2357 pw.print(dalvikFree); pw.print(',');
2358 pw.print("N/A,");
2359 pw.print(nativeFree + dalvikFree); pw.print(',');
2360
2361 // Heap info - proportional set size
2362 pw.print(memInfo.nativePss); pw.print(',');
2363 pw.print(memInfo.dalvikPss); pw.print(',');
2364 pw.print(memInfo.otherPss); pw.print(',');
2365 pw.print(memInfo.getTotalPss()); pw.print(',');
2366
2367 // Heap info - swappable set size
2368 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2369 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2370 pw.print(memInfo.otherSwappablePss); pw.print(',');
2371 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2372
2373 // Heap info - shared dirty
2374 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2375 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2376 pw.print(memInfo.otherSharedDirty); pw.print(',');
2377 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2378
2379 // Heap info - shared clean
2380 pw.print(memInfo.nativeSharedClean); pw.print(',');
2381 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2382 pw.print(memInfo.otherSharedClean); pw.print(',');
2383 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2384
2385 // Heap info - private Dirty
2386 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2387 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2388 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2389 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2390
2391 // Heap info - private Clean
2392 pw.print(memInfo.nativePrivateClean); pw.print(',');
2393 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2394 pw.print(memInfo.otherPrivateClean); pw.print(',');
2395 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2396
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002397 // Heap info - swapped out
2398 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2399 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2400 pw.print(memInfo.otherSwappedOut); pw.print(',');
2401 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2402
2403 // Heap info - swapped out pss
2404 if (memInfo.hasSwappedOutPss) {
2405 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2406 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2407 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2408 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2409 } else {
2410 pw.print("N/A,");
2411 pw.print("N/A,");
2412 pw.print("N/A,");
2413 pw.print("N/A,");
2414 }
2415
Dianne Hackborne77187d2013-10-25 16:32:41 -07002416 // Heap info - other areas
2417 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2418 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2419 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2420 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2421 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2422 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2423 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2424 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002425 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2426 if (memInfo.hasSwappedOutPss) {
2427 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2428 } else {
2429 pw.print("N/A,");
2430 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002431 }
2432 return;
2433 }
2434
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002435 if (!dumpSummaryOnly) {
2436 if (dumpFullInfo) {
2437 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002438 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2439 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002440 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
Martijn Coenene0764852016-01-07 17:04:22 -08002441 "Clean", "Clean", "Dirty",
2442 "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002443 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
2444 "------", "------", "------", "------", "------", "------");
2445 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2446 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2447 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002448 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002449 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002450 nativeMax, nativeAllocated, nativeFree);
2451 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2452 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2453 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002454 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002455 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002456 dalvikMax, dalvikAllocated, dalvikFree);
2457 } else {
2458 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002459 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2460 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002461 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
2462 "Clean", "Dirty", "Size", "Alloc", "Free");
2463 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
2464 "------", "------", "------", "------", "------");
2465 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2466 memInfo.nativePrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002467 memInfo.nativePrivateClean,
2468 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
2469 memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002470 nativeMax, nativeAllocated, nativeFree);
2471 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2472 memInfo.dalvikPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002473 memInfo.dalvikPrivateClean,
2474 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
2475 memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002476 dalvikMax, dalvikAllocated, dalvikFree);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002477 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002478
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002479 int otherPss = memInfo.otherPss;
2480 int otherSwappablePss = memInfo.otherSwappablePss;
2481 int otherSharedDirty = memInfo.otherSharedDirty;
2482 int otherPrivateDirty = memInfo.otherPrivateDirty;
2483 int otherSharedClean = memInfo.otherSharedClean;
2484 int otherPrivateClean = memInfo.otherPrivateClean;
2485 int otherSwappedOut = memInfo.otherSwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002486 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002487
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002488 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002489 final int myPss = memInfo.getOtherPss(i);
2490 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2491 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2492 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2493 final int mySharedClean = memInfo.getOtherSharedClean(i);
2494 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2495 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002496 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002497 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002498 || mySharedClean != 0 || myPrivateClean != 0
2499 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002500 if (dumpFullInfo) {
2501 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2502 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002503 mySharedClean, myPrivateClean,
2504 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2505 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002506 } else {
2507 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2508 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002509 myPrivateClean,
2510 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2511 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002512 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002513 otherPss -= myPss;
2514 otherSwappablePss -= mySwappablePss;
2515 otherSharedDirty -= mySharedDirty;
2516 otherPrivateDirty -= myPrivateDirty;
2517 otherSharedClean -= mySharedClean;
2518 otherPrivateClean -= myPrivateClean;
2519 otherSwappedOut -= mySwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002520 otherSwappedOutPss -= mySwappedOutPss;
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002521 }
2522 }
2523
2524 if (dumpFullInfo) {
2525 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
2526 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002527 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
2528 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002529 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
2530 memInfo.getTotalSwappablePss(),
2531 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2532 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
Thierry Strudel9b511602016-02-25 17:46:38 -08002533 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
2534 memInfo.getTotalSwappedOut(),
Martijn Coenene0764852016-01-07 17:04:22 -08002535 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
2536 nativeFree+dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002537 } else {
2538 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
Martijn Coenene0764852016-01-07 17:04:22 -08002539 otherPrivateDirty, otherPrivateClean,
2540 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002541 "", "", "");
2542 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
2543 memInfo.getTotalPrivateDirty(),
2544 memInfo.getTotalPrivateClean(),
Martijn Coenene0764852016-01-07 17:04:22 -08002545 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002546 memInfo.getTotalSwappedOut(),
2547 nativeMax+dalvikMax,
2548 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
2549 }
2550
2551 if (dumpDalvik) {
2552 pw.println(" ");
2553 pw.println(" Dalvik Details");
2554
2555 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
2556 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
2557 final int myPss = memInfo.getOtherPss(i);
2558 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2559 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2560 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2561 final int mySharedClean = memInfo.getOtherSharedClean(i);
2562 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2563 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002564 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002565 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002566 || mySharedClean != 0 || myPrivateClean != 0
2567 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002568 if (dumpFullInfo) {
2569 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2570 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002571 mySharedClean, myPrivateClean,
2572 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2573 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002574 } else {
2575 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2576 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002577 myPrivateClean,
2578 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2579 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002580 }
2581 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002582 }
2583 }
2584 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002585
2586 pw.println(" ");
2587 pw.println(" App Summary");
2588 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "Pss(KB)");
2589 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "------");
2590 printRow(pw, ONE_COUNT_COLUMN,
2591 "Java Heap:", memInfo.getSummaryJavaHeap());
2592 printRow(pw, ONE_COUNT_COLUMN,
2593 "Native Heap:", memInfo.getSummaryNativeHeap());
2594 printRow(pw, ONE_COUNT_COLUMN,
2595 "Code:", memInfo.getSummaryCode());
2596 printRow(pw, ONE_COUNT_COLUMN,
2597 "Stack:", memInfo.getSummaryStack());
2598 printRow(pw, ONE_COUNT_COLUMN,
2599 "Graphics:", memInfo.getSummaryGraphics());
2600 printRow(pw, ONE_COUNT_COLUMN,
2601 "Private Other:", memInfo.getSummaryPrivateOther());
2602 printRow(pw, ONE_COUNT_COLUMN,
2603 "System:", memInfo.getSummarySystem());
2604 pw.println(" ");
Martijn Coenene0764852016-01-07 17:04:22 -08002605 if (memInfo.hasSwappedOutPss) {
2606 printRow(pw, TWO_COUNT_COLUMNS,
2607 "TOTAL:", memInfo.getSummaryTotalPss(),
2608 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
2609 } else {
2610 printRow(pw, TWO_COUNT_COLUMNS,
2611 "TOTAL:", memInfo.getSummaryTotalPss(),
2612 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
2613 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002614 }
2615
Kweku Adams598e9a22017-11-02 17:12:20 -07002616 /**
2617 * Dump heap info to proto.
2618 *
2619 * @param hasSwappedOutPss determines whether to use dirtySwap or dirtySwapPss
2620 */
Kweku Adams983829f2017-12-06 14:53:50 -08002621 private static void dumpMemoryInfo(ProtoOutputStream proto, long fieldId, String name,
Kweku Adams598e9a22017-11-02 17:12:20 -07002622 int pss, int cleanPss, int sharedDirty, int privateDirty,
2623 int sharedClean, int privateClean,
2624 boolean hasSwappedOutPss, int dirtySwap, int dirtySwapPss) {
2625 final long token = proto.start(fieldId);
2626
Yi Jin2b30f322018-02-20 15:41:47 -08002627 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.NAME, name);
2628 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_PSS_KB, pss);
2629 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.CLEAN_PSS_KB, cleanPss);
2630 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_DIRTY_KB, sharedDirty);
2631 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_DIRTY_KB, privateDirty);
2632 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_CLEAN_KB, sharedClean);
2633 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_CLEAN_KB, privateClean);
Kweku Adams598e9a22017-11-02 17:12:20 -07002634 if (hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002635 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_PSS_KB, dirtySwapPss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002636 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002637 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_KB, dirtySwap);
Kweku Adams598e9a22017-11-02 17:12:20 -07002638 }
2639
2640 proto.end(token);
2641 }
2642
2643 /**
2644 * Dump mem info data to proto.
2645 */
2646 public static void dumpMemInfoTable(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
2647 boolean dumpDalvik, boolean dumpSummaryOnly,
2648 long nativeMax, long nativeAllocated, long nativeFree,
2649 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2650
2651 if (!dumpSummaryOnly) {
Yi Jin2b30f322018-02-20 15:41:47 -08002652 final long nhToken = proto.start(MemInfoDumpProto.ProcessMemory.NATIVE_HEAP);
2653 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Native Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002654 memInfo.nativePss, memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2655 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
2656 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss,
2657 memInfo.nativeSwappedOut, memInfo.nativeSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002658 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax);
2659 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, nativeAllocated);
2660 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002661 proto.end(nhToken);
2662
Yi Jin2b30f322018-02-20 15:41:47 -08002663 final long dvToken = proto.start(MemInfoDumpProto.ProcessMemory.DALVIK_HEAP);
2664 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Dalvik Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002665 memInfo.dalvikPss, memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2666 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
2667 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss,
2668 memInfo.dalvikSwappedOut, memInfo.dalvikSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002669 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, dalvikMax);
2670 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, dalvikAllocated);
2671 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002672 proto.end(dvToken);
2673
2674 int otherPss = memInfo.otherPss;
2675 int otherSwappablePss = memInfo.otherSwappablePss;
2676 int otherSharedDirty = memInfo.otherSharedDirty;
2677 int otherPrivateDirty = memInfo.otherPrivateDirty;
2678 int otherSharedClean = memInfo.otherSharedClean;
2679 int otherPrivateClean = memInfo.otherPrivateClean;
2680 int otherSwappedOut = memInfo.otherSwappedOut;
2681 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
2682
2683 for (int i = 0; i < Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2684 final int myPss = memInfo.getOtherPss(i);
2685 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2686 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2687 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2688 final int mySharedClean = memInfo.getOtherSharedClean(i);
2689 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2690 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2691 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2692 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2693 || mySharedClean != 0 || myPrivateClean != 0
2694 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002695 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.OTHER_HEAPS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002696 Debug.MemoryInfo.getOtherLabel(i),
2697 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2698 mySharedClean, myPrivateClean,
2699 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2700
2701 otherPss -= myPss;
2702 otherSwappablePss -= mySwappablePss;
2703 otherSharedDirty -= mySharedDirty;
2704 otherPrivateDirty -= myPrivateDirty;
2705 otherSharedClean -= mySharedClean;
2706 otherPrivateClean -= myPrivateClean;
2707 otherSwappedOut -= mySwappedOut;
2708 otherSwappedOutPss -= mySwappedOutPss;
2709 }
2710 }
2711
Yi Jin2b30f322018-02-20 15:41:47 -08002712 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.UNKNOWN_HEAP, "Unknown",
Kweku Adams598e9a22017-11-02 17:12:20 -07002713 otherPss, otherSwappablePss,
2714 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
2715 memInfo.hasSwappedOutPss, otherSwappedOut, otherSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002716 final long tToken = proto.start(MemInfoDumpProto.ProcessMemory.TOTAL_HEAP);
2717 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "TOTAL",
Kweku Adams598e9a22017-11-02 17:12:20 -07002718 memInfo.getTotalPss(), memInfo.getTotalSwappablePss(),
2719 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2720 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
2721 memInfo.hasSwappedOutPss, memInfo.getTotalSwappedOut(),
2722 memInfo.getTotalSwappedOutPss());
Yi Jin2b30f322018-02-20 15:41:47 -08002723 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB,
2724 nativeMax + dalvikMax);
2725 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002726 nativeAllocated + dalvikAllocated);
Yi Jin2b30f322018-02-20 15:41:47 -08002727 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB,
2728 nativeFree + dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002729 proto.end(tToken);
2730
2731 if (dumpDalvik) {
2732 for (int i = Debug.MemoryInfo.NUM_OTHER_STATS;
2733 i < Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS;
2734 i++) {
2735 final int myPss = memInfo.getOtherPss(i);
2736 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2737 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2738 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2739 final int mySharedClean = memInfo.getOtherSharedClean(i);
2740 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2741 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2742 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2743 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2744 || mySharedClean != 0 || myPrivateClean != 0
2745 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002746 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.DALVIK_DETAILS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002747 Debug.MemoryInfo.getOtherLabel(i),
2748 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2749 mySharedClean, myPrivateClean,
2750 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2751 }
2752 }
2753 }
2754 }
2755
Yi Jin2b30f322018-02-20 15:41:47 -08002756 final long asToken = proto.start(MemInfoDumpProto.ProcessMemory.APP_SUMMARY);
2757 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002758 memInfo.getSummaryJavaHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002759 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002760 memInfo.getSummaryNativeHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002761 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_PSS_KB,
2762 memInfo.getSummaryCode());
2763 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_PSS_KB,
2764 memInfo.getSummaryStack());
2765 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002766 memInfo.getSummaryGraphics());
Yi Jin2b30f322018-02-20 15:41:47 -08002767 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.PRIVATE_OTHER_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002768 memInfo.getSummaryPrivateOther());
Yi Jin2b30f322018-02-20 15:41:47 -08002769 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.SYSTEM_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002770 memInfo.getSummarySystem());
2771 if (memInfo.hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002772 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002773 memInfo.getSummaryTotalSwapPss());
2774 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002775 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002776 memInfo.getSummaryTotalSwap());
2777 }
2778 proto.end(asToken);
2779 }
2780
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002781 @UnsupportedAppUsage
Jeff Hamilton52d32032011-01-08 15:31:26 -06002782 public void registerOnActivityPausedListener(Activity activity,
2783 OnActivityPausedListener listener) {
2784 synchronized (mOnPauseListeners) {
2785 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2786 if (list == null) {
2787 list = new ArrayList<OnActivityPausedListener>();
2788 mOnPauseListeners.put(activity, list);
2789 }
2790 list.add(listener);
2791 }
2792 }
2793
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002794 @UnsupportedAppUsage
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08002795 public void unregisterOnActivityPausedListener(Activity activity,
2796 OnActivityPausedListener listener) {
2797 synchronized (mOnPauseListeners) {
2798 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2799 if (list != null) {
2800 list.remove(listener);
2801 }
2802 }
2803 }
2804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 public final ActivityInfo resolveActivityInfo(Intent intent) {
2806 ActivityInfo aInfo = intent.resolveActivityInfo(
2807 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2808 if (aInfo == null) {
2809 // Throw an exception.
2810 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002811 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 }
2813 return aInfo;
2814 }
Bob Leee5408332009-09-04 18:31:17 -07002815
Mathew Inwood45d2c252018-09-14 12:35:36 +01002816 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002819 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002820 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002822 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 r.intent = intent;
2824 r.state = state;
2825 r.parent = parent;
2826 r.embeddedID = id;
2827 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002828 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 if (localLOGV) {
2830 ComponentName compname = intent.getComponent();
2831 String name;
2832 if (compname != null) {
2833 name = compname.toShortString();
2834 } else {
2835 name = "(Intent " + intent + ").getComponent() returned null";
2836 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002837 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 + ", comp=" + name
2839 + ", token=" + token);
2840 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002841 // TODO(lifecycler): Can't switch to use #handleLaunchActivity() because it will try to
2842 // call #reportSizeConfigurations(), but the server might not know anything about the
2843 // activity if it was launched from LocalAcvitivyManager.
Andrii Kulian770c4032018-05-02 18:40:59 -07002844 return performLaunchActivity(r, null /* customIntent */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 }
2846
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002847 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 public final Activity getActivity(IBinder token) {
2849 return mActivities.get(token).activity;
2850 }
2851
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002852 @Override
2853 public ActivityClientRecord getActivityClient(IBinder token) {
2854 return mActivities.get(token);
2855 }
2856
Mathew Inwood4fb17d12018-08-14 14:25:44 +01002857 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 public final void sendActivityResult(
2859 IBinder token, String id, int requestCode,
2860 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002861 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07002862 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2864 list.add(new ResultInfo(id, requestCode, resultCode, data));
Andrii Kulian9c5ea9c2017-12-07 09:31:01 -08002865 final ClientTransaction clientTransaction = ClientTransaction.obtain(mAppThread, token);
2866 clientTransaction.addCallback(ActivityResultItem.obtain(list));
Andrii Kulian446e8242017-10-26 15:17:29 -07002867 try {
2868 mAppThread.scheduleTransaction(clientTransaction);
2869 } catch (RemoteException e) {
2870 // Local scheduling
2871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 }
2873
Andrii Kulian914aa7d2018-03-19 21:51:53 -07002874 @Override
2875 TransactionExecutor getTransactionExecutor() {
2876 return mTransactionExecutor;
2877 }
2878
Andrii Kulian446e8242017-10-26 15:17:29 -07002879 void sendMessage(int what, Object obj) {
Jeff Brown9ef09972013-10-15 20:49:59 -07002880 sendMessage(what, obj, 0, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 }
2882
Jeff Brown9ef09972013-10-15 20:49:59 -07002883 private void sendMessage(int what, Object obj, int arg1) {
2884 sendMessage(what, obj, arg1, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 }
2886
Jeff Brown9ef09972013-10-15 20:49:59 -07002887 private void sendMessage(int what, Object obj, int arg1, int arg2) {
2888 sendMessage(what, obj, arg1, arg2, false);
2889 }
2890
2891 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
2892 if (DEBUG_MESSAGES) Slog.v(
2893 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2894 + ": " + arg1 + " / " + obj);
2895 Message msg = Message.obtain();
2896 msg.what = what;
2897 msg.obj = obj;
2898 msg.arg1 = arg1;
2899 msg.arg2 = arg2;
2900 if (async) {
2901 msg.setAsynchronous(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
Jeff Brown9ef09972013-10-15 20:49:59 -07002903 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 }
2905
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07002906 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
2907 if (DEBUG_MESSAGES) Slog.v(
2908 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
2909 "seq= " + seq);
2910 Message msg = Message.obtain();
2911 msg.what = what;
2912 SomeArgs args = SomeArgs.obtain();
2913 args.arg1 = obj;
2914 args.argi1 = arg1;
2915 args.argi2 = arg2;
2916 args.argi3 = seq;
2917 msg.obj = args;
2918 mH.sendMessage(msg);
2919 }
2920
Dianne Hackborn21556372010-02-04 16:34:40 -08002921 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 String what) {
2923 ContextCleanupInfo cci = new ContextCleanupInfo();
2924 cci.context = context;
2925 cci.who = who;
2926 cci.what = what;
Jeff Brown9ef09972013-10-15 20:49:59 -07002927 sendMessage(H.CLEAN_UP_CONTEXT, cci);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 }
2929
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002930 /** Core implementation of activity launch. */
Andrii Kulian770c4032018-05-02 18:40:59 -07002931 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 ActivityInfo aInfo = r.activityInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00002933 if (r.packageInfo == null) {
2934 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 Context.CONTEXT_INCLUDE_CODE);
2936 }
Bob Leee5408332009-09-04 18:31:17 -07002937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 ComponentName component = r.intent.getComponent();
2939 if (component == null) {
2940 component = r.intent.resolveActivity(
2941 mInitialApplication.getPackageManager());
2942 r.intent.setComponent(component);
2943 }
2944
2945 if (r.activityInfo.targetActivity != null) {
2946 component = new ComponentName(r.activityInfo.packageName,
2947 r.activityInfo.targetActivity);
2948 }
2949
Adam Lesinski4e862812016-11-21 16:02:24 -08002950 ContextImpl appContext = createBaseContextForActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 Activity activity = null;
2952 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08002953 java.lang.ClassLoader cl = appContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04002954 activity = mInstrumentation.newActivity(
2955 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002956 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 r.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01002958 r.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 if (r.state != null) {
2960 r.state.setClassLoader(cl);
2961 }
2962 } catch (Exception e) {
2963 if (!mInstrumentation.onException(activity, e)) {
2964 throw new RuntimeException(
2965 "Unable to instantiate activity " + component
2966 + ": " + e.toString(), e);
2967 }
2968 }
2969
2970 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002971 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002972
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002973 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
2974 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 TAG, r + ": app=" + app
2976 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002977 + ", pkg=" + r.packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 + ", comp=" + r.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002979 + ", dir=" + r.packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980
2981 if (activity != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002983 Configuration config = new Configuration(mCompatConfiguration);
Andrii Kuliand0ad9382016-04-18 20:54:20 -07002984 if (r.overrideConfig != null) {
2985 config.updateFrom(r.overrideConfig);
2986 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002987 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002988 + r.activityInfo.name + " with config " + config);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07002989 Window window = null;
2990 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
2991 window = r.mPendingRemoveWindow;
2992 r.mPendingRemoveWindow = null;
2993 r.mPendingRemoveWindowManager = null;
2994 }
Adam Lesinski4e862812016-11-21 16:02:24 -08002995 appContext.setOuterContext(activity);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002996 activity.attach(appContext, this, getInstrumentation(), r.token,
2997 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Craig Mautner233ceee2014-05-09 17:05:11 -07002998 r.embeddedID, r.lastNonConfigurationInstances, config,
Andrii Kulian51c1b672017-04-07 18:39:32 -07002999 r.referrer, r.voiceInteractor, window, r.configCallback);
Bob Leee5408332009-09-04 18:31:17 -07003000
Andrii Kulian770c4032018-05-02 18:40:59 -07003001 if (customIntent != null) {
3002 activity.mIntent = customIntent;
3003 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003004 r.lastNonConfigurationInstances = null;
Sudheer Shanka84a48952017-03-08 18:19:01 -08003005 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 activity.mStartedActivity = false;
3007 int theme = r.activityInfo.getThemeResource();
3008 if (theme != 0) {
3009 activity.setTheme(theme);
3010 }
3011
3012 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07003013 if (r.isPersistable()) {
3014 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
3015 } else {
3016 mInstrumentation.callActivityOnCreate(activity, r.state);
3017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 if (!activity.mCalled) {
3019 throw new SuperNotCalledException(
3020 "Activity " + r.intent.getComponent().toShortString() +
3021 " did not call through to super.onCreate()");
3022 }
3023 r.activity = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003025 r.setState(ON_CREATE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026
3027 mActivities.put(r.token, r);
3028
3029 } catch (SuperNotCalledException e) {
3030 throw e;
3031
3032 } catch (Exception e) {
3033 if (!mInstrumentation.onException(activity, e)) {
3034 throw new RuntimeException(
3035 "Unable to start activity " + component
3036 + ": " + e.toString(), e);
3037 }
3038 }
3039
3040 return activity;
3041 }
3042
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003043 @Override
3044 public void handleStartActivity(ActivityClientRecord r,
3045 PendingTransactionActions pendingActions) {
3046 final Activity activity = r.activity;
3047 if (r.activity == null) {
3048 // TODO(lifecycler): What do we do in this case?
3049 return;
3050 }
3051 if (!r.stopped) {
3052 throw new IllegalStateException("Can't start activity that is not stopped.");
3053 }
3054 if (r.activity.mFinished) {
3055 // TODO(lifecycler): How can this happen?
3056 return;
3057 }
3058
3059 // Start
Andrii Kuliand25680c2018-02-21 15:16:58 -08003060 activity.performStart("handleStartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003061 r.setState(ON_START);
3062
3063 if (pendingActions == null) {
3064 // No more work to do.
3065 return;
3066 }
3067
3068 // Restore instance state
3069 if (pendingActions.shouldRestoreInstanceState()) {
3070 if (r.isPersistable()) {
3071 if (r.state != null || r.persistentState != null) {
3072 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
3073 r.persistentState);
3074 }
3075 } else if (r.state != null) {
3076 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
3077 }
3078 }
3079
3080 // Call postOnCreate()
3081 if (pendingActions.shouldCallOnPostCreate()) {
3082 activity.mCalled = false;
3083 if (r.isPersistable()) {
3084 mInstrumentation.callActivityOnPostCreate(activity, r.state,
3085 r.persistentState);
3086 } else {
3087 mInstrumentation.callActivityOnPostCreate(activity, r.state);
3088 }
3089 if (!activity.mCalled) {
3090 throw new SuperNotCalledException(
3091 "Activity " + r.intent.getComponent().toShortString()
3092 + " did not call through to super.onPostCreate()");
3093 }
3094 }
3095 }
3096
Sudheer Shanka84a48952017-03-08 18:19:01 -08003097 /**
3098 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
3099 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
3100 * network rules to get updated.
3101 */
3102 private void checkAndBlockForNetworkAccess() {
3103 synchronized (mNetworkPolicyLock) {
3104 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
3105 try {
3106 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
3107 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
3108 } catch (RemoteException ignored) {}
3109 }
3110 }
3111 }
3112
Adam Lesinski4e862812016-11-21 16:02:24 -08003113 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
3114 final int displayId;
Craig Mautnere0a38842013-12-16 16:14:02 -08003115 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003116 displayId = ActivityManager.getService().getActivityDisplayId(r.token);
Craig Mautnere0a38842013-12-16 16:14:02 -08003117 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003118 throw e.rethrowFromSystemServer();
Craig Mautnere0a38842013-12-16 16:14:02 -08003119 }
Jeff Brownefd43bd2012-09-21 17:02:35 -07003120
Wale Ogunwale7c726682015-02-06 17:34:28 -08003121 ContextImpl appContext = ContextImpl.createActivityContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00003122 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
Wale Ogunwale7c726682015-02-06 17:34:28 -08003123
3124 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
Jeff Brownefd43bd2012-09-21 17:02:35 -07003125 // For debugging purposes, if the activity's package name contains the value of
3126 // the "debug.use-second-display" system property as a substring, then show
3127 // its content on a secondary display if there is one.
Jeff Brownefd43bd2012-09-21 17:02:35 -07003128 String pkgName = SystemProperties.get("debug.second-display.pkg");
3129 if (pkgName != null && !pkgName.isEmpty()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003130 && r.packageInfo.mPackageName.contains(pkgName)) {
Wale Ogunwale7c726682015-02-06 17:34:28 -08003131 for (int id : dm.getDisplayIds()) {
3132 if (id != Display.DEFAULT_DISPLAY) {
Wale Ogunwale26698512015-06-05 16:55:33 -07003133 Display display =
Bryce Lee609bf652017-02-09 16:50:13 -08003134 dm.getCompatibleDisplay(id, appContext.getResources());
Adam Lesinski4e862812016-11-21 16:02:24 -08003135 appContext = (ContextImpl) appContext.createDisplayContext(display);
Jeff Brownefd43bd2012-09-21 17:02:35 -07003136 break;
3137 }
3138 }
3139 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003140 return appContext;
Jeff Brownefd43bd2012-09-21 17:02:35 -07003141 }
3142
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003143 /**
3144 * Extended implementation of activity launch. Used when server requests a launch or relaunch.
3145 */
Andrii Kulian446e8242017-10-26 15:17:29 -07003146 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003147 public Activity handleLaunchActivity(ActivityClientRecord r,
Andrii Kulian770c4032018-05-02 18:40:59 -07003148 PendingTransactionActions pendingActions, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 // If we are getting ready to gc after going to the background, well
3150 // we are back active so skip it.
3151 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003152 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153
Jeff Hao1b012d32014-08-20 10:35:34 -07003154 if (r.profilerInfo != null) {
3155 mProfiler.setProfiler(r.profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003156 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003157 }
3158
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003159 // Make sure we are running with the most recent config.
3160 handleConfigurationChanged(null, null);
3161
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003162 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 TAG, "Handling launch of " + r);
Adam Powellcfbe9be2013-11-06 14:58:58 -08003164
Chet Haase0d1c27a2014-11-03 18:35:16 +00003165 // Initialize before creating the activity
Jesse Hallc37984f2017-05-23 16:55:08 -07003166 if (!ThreadedRenderer.sRendererDisabled) {
3167 GraphicsEnvironment.earlyInitEGL();
3168 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00003169 WindowManagerGlobal.initialize();
3170
Andrii Kulian770c4032018-05-02 18:40:59 -07003171 final Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172
3173 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003174 r.createdConfig = new Configuration(mConfiguration);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003175 reportSizeConfigurations(r);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003176 if (!r.activity.mFinished && pendingActions != null) {
3177 pendingActions.setOldState(r.state);
3178 pendingActions.setRestoreInstanceState(true);
3179 pendingActions.setCallOnPostCreate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 }
3181 } else {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003182 // 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 -08003183 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003184 ActivityManager.getService()
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003185 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
3186 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003188 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 }
3190 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003191
3192 return a;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 }
3194
Filip Gruszczynski23493322015-07-29 17:02:59 -07003195 private void reportSizeConfigurations(ActivityClientRecord r) {
3196 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
3197 if (configurations == null) {
3198 return;
3199 }
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003200 SparseIntArray horizontal = new SparseIntArray();
3201 SparseIntArray vertical = new SparseIntArray();
3202 SparseIntArray smallest = new SparseIntArray();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003203 for (int i = configurations.length - 1; i >= 0; i--) {
3204 Configuration config = configurations[i];
3205 if (config.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003206 vertical.put(config.screenHeightDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003207 }
3208 if (config.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003209 horizontal.put(config.screenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003210 }
3211 if (config.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003212 smallest.put(config.smallestScreenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003213 }
3214 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003215 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003216 ActivityManager.getService().reportSizeConfigurations(r.token,
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003217 horizontal.copyKeys(), vertical.copyKeys(), smallest.copyKeys());
Filip Gruszczynski23493322015-07-29 17:02:59 -07003218 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003219 throw ex.rethrowFromSystemServer();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003220 }
3221
3222 }
3223
Dianne Hackborn85d558c2014-11-04 10:31:54 -08003224 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 final int N = intents.size();
3226 for (int i=0; i<N; i++) {
Dianne Hackborna01a0fa2014-12-02 10:33:14 -08003227 ReferrerIntent intent = intents.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 intent.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003229 intent.prepareToEnterProcess();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003230 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
3232 }
3233 }
3234
Mathew Inwood4fb17d12018-08-14 14:25:44 +01003235 @UnsupportedAppUsage
Wale Ogunwale826c7062016-09-13 08:25:54 -07003236 void performNewIntents(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3237 final ActivityClientRecord r = mActivities.get(token);
3238 if (r == null) {
3239 return;
3240 }
3241
3242 final boolean resumed = !r.paused;
3243 if (resumed) {
3244 r.activity.mTemporaryPause = true;
3245 mInstrumentation.callActivityOnPause(r.activity);
3246 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003247 checkAndBlockForNetworkAccess();
Wale Ogunwale826c7062016-09-13 08:25:54 -07003248 deliverNewIntents(r, intents);
3249 if (resumed) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08003250 r.activity.performResume(false, "performNewIntents");
Wale Ogunwale826c7062016-09-13 08:25:54 -07003251 r.activity.mTemporaryPause = false;
3252 }
3253
3254 if (r.paused && andPause) {
3255 // In this case the activity was in the paused state when we delivered the intent,
3256 // to guarantee onResume gets called after onNewIntent we temporarily resume the
3257 // activity and pause again as the caller wanted.
3258 performResumeActivity(token, false, "performNewIntents");
3259 performPauseActivityIfNeeded(r, "performNewIntents");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 }
3261 }
Bob Leee5408332009-09-04 18:31:17 -07003262
Andrii Kulian446e8242017-10-26 15:17:29 -07003263 @Override
3264 public void handleNewIntent(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3265 performNewIntents(token, intents, andPause);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 }
3267
Adam Skorydfc7fd72013-08-05 19:23:41 -07003268 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003269 // Filling for autofill has a few differences:
Felipe Leme1ca634a2016-11-28 17:21:21 -08003270 // - it does not need an AssistContent
3271 // - it does not call onProvideAssistData()
3272 // - it needs an IAutoFillCallback
Felipe Leme640f30a2017-03-06 15:44:06 -08003273 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
Felipe Leme1ca634a2016-11-28 17:21:21 -08003274
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003275 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani4f128e42016-05-10 11:44:12 -07003276 if (mLastSessionId != cmd.sessionId) {
3277 // Clear the existing structures
3278 mLastSessionId = cmd.sessionId;
3279 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
3280 AssistStructure structure = mLastAssistStructures.get(i).get();
3281 if (structure != null) {
3282 structure.clearSendChannel();
3283 }
3284 mLastAssistStructures.remove(i);
Dianne Hackborn782d4982015-07-08 17:36:37 -07003285 }
3286 }
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003287
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003288 Bundle data = new Bundle();
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003289 AssistStructure structure = null;
Felipe Leme640f30a2017-03-06 15:44:06 -08003290 AssistContent content = forAutofill ? null : new AssistContent();
Amith Yamasani858f98d2017-02-22 12:59:53 -08003291 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003292 ActivityClientRecord r = mActivities.get(cmd.activityToken);
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003293 Uri referrer = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003294 if (r != null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003295 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003296 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003297 r.activity.onProvideAssistData(data);
Felipe Leme6d553872016-12-08 17:13:25 -08003298 referrer = r.activity.onProvideReferrer();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003299 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003300 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill) {
Svet Ganovfd31f852017-04-26 15:54:27 -07003301 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
Adam Skory4aaed142015-04-22 11:29:31 -06003302 Intent activityIntent = r.activity.getIntent();
Felipe Leme6d553872016-12-08 17:13:25 -08003303 boolean notSecure = r.window == null ||
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003304 (r.window.getAttributes().flags
Felipe Leme6d553872016-12-08 17:13:25 -08003305 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3306 if (activityIntent != null && notSecure) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003307 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003308 Intent intent = new Intent(activityIntent);
3309 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3310 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3311 intent.removeUnsafeExtras();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003312 content.setDefaultIntent(intent);
3313 }
Adam Skory4aaed142015-04-22 11:29:31 -06003314 } else {
Felipe Leme640f30a2017-03-06 15:44:06 -08003315 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003316 content.setDefaultIntent(new Intent());
3317 }
Adam Skory4aaed142015-04-22 11:29:31 -06003318 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003319 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003320 r.activity.onProvideAssistContent(content);
3321 }
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07003322 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003323 }
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003324 if (structure == null) {
3325 structure = new AssistStructure();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003326 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08003327
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003328 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani858f98d2017-02-22 12:59:53 -08003329
3330 structure.setAcquisitionStartTime(startTime);
3331 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3332
Amith Yamasani4f128e42016-05-10 11:44:12 -07003333 mLastAssistStructures.add(new WeakReference<>(structure));
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003334 IActivityManager mgr = ActivityManager.getService();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003335 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003336 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003337 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003338 throw e.rethrowFromSystemServer();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003339 }
3340 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07003341
3342 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
3343 ActivityClientRecord r = mActivities.get(token);
3344 if (r != null) {
3345 r.activity.onTranslucentConversionComplete(drawComplete);
3346 }
3347 }
3348
Craig Mautnereb8abf72014-07-02 15:04:09 -07003349 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
3350 ActivityClientRecord r = mActivities.get(token);
3351 if (r != null) {
3352 r.activity.onNewActivityOptions(options);
3353 }
3354 }
3355
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003356 public void handleInstallProvider(ProviderInfo info) {
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003357 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3358 try {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003359 installContentProviders(mInitialApplication, Arrays.asList(info));
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003360 } finally {
3361 StrictMode.setThreadPolicy(oldPolicy);
3362 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003363 }
3364
Craig Mautner8746a472014-07-24 15:12:54 -07003365 private void handleEnterAnimationComplete(IBinder token) {
3366 ActivityClientRecord r = mActivities.get(token);
3367 if (r != null) {
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08003368 r.activity.dispatchEnterAnimationComplete();
Craig Mautner8746a472014-07-24 15:12:54 -07003369 }
3370 }
3371
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04003372 private void handleStartBinderTracking() {
3373 Binder.enableTracing();
3374 }
3375
3376 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
3377 try {
3378 Binder.disableTracing();
3379 Binder.getTransactionTracker().writeTracesToFile(fd);
3380 } finally {
3381 IoUtils.closeQuietly(fd);
3382 Binder.getTransactionTracker().clearTraces();
3383 }
3384 }
3385
Andrii Kulian446e8242017-10-26 15:17:29 -07003386 @Override
3387 public void handleMultiWindowModeChanged(IBinder token, boolean isInMultiWindowMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003388 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003389 final ActivityClientRecord r = mActivities.get(token);
3390 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003391 final Configuration newConfig = new Configuration(mConfiguration);
3392 if (overrideConfig != null) {
3393 newConfig.updateFrom(overrideConfig);
3394 }
3395 r.activity.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003396 }
3397 }
3398
Andrii Kulian446e8242017-10-26 15:17:29 -07003399 @Override
3400 public void handlePictureInPictureModeChanged(IBinder token, boolean isInPipMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003401 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003402 final ActivityClientRecord r = mActivities.get(token);
3403 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003404 final Configuration newConfig = new Configuration(mConfiguration);
3405 if (overrideConfig != null) {
3406 newConfig.updateFrom(overrideConfig);
3407 }
3408 r.activity.dispatchPictureInPictureModeChanged(isInPipMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003409 }
3410 }
3411
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003412 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
3413 final ActivityClientRecord r = mActivities.get(token);
3414 if (r != null) {
3415 r.voiceInteractor = interactor;
3416 r.activity.setVoiceInteractor(interactor);
3417 if (interactor == null) {
3418 r.activity.onLocalVoiceInteractionStopped();
3419 } else {
3420 r.activity.onLocalVoiceInteractionStarted();
3421 }
3422 }
3423 }
3424
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003425 private static boolean attemptAttachAgent(String agent, ClassLoader classLoader) {
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003426 try {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003427 VMDebug.attachAgent(agent, classLoader);
3428 return true;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003429 } catch (IOException e) {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003430 Slog.e(TAG, "Attaching agent with " + classLoader + " failed: " + agent);
3431 return false;
3432 }
3433 }
3434
3435 static void handleAttachAgent(String agent, LoadedApk loadedApk) {
3436 ClassLoader classLoader = loadedApk != null ? loadedApk.getClassLoader() : null;
3437 if (attemptAttachAgent(agent, classLoader)) {
3438 return;
3439 }
3440 if (classLoader != null) {
3441 attemptAttachAgent(agent, null);
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003442 }
3443 }
3444
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003445 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
3446
3447 /**
3448 * Return the Intent that's currently being handled by a
3449 * BroadcastReceiver on this thread, or null if none.
3450 * @hide
3451 */
3452 public static Intent getIntentBeingBroadcast() {
3453 return sCurrentBroadcastIntent.get();
3454 }
3455
Mathew Inwood55418ea2018-12-20 15:30:45 +00003456 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Romain Guy65b345f2011-07-27 18:51:50 -07003457 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 // If we are getting ready to gc after going to the background, well
3459 // we are back active so skip it.
3460 unscheduleGcIdler();
3461
3462 String component = data.intent.getComponent().getClassName();
3463
Todd Kennedy233a0b12018-01-29 20:30:24 +00003464 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003465 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003467 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468
Adam Lesinski4e862812016-11-21 16:02:24 -08003469 Application app;
Romain Guy65b345f2011-07-27 18:51:50 -07003470 BroadcastReceiver receiver;
Adam Lesinski4e862812016-11-21 16:02:24 -08003471 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003473 app = packageInfo.makeApplication(false, mInstrumentation);
Adam Lesinski4e862812016-11-21 16:02:24 -08003474 context = (ContextImpl) app.getBaseContext();
3475 if (data.info.splitName != null) {
3476 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
3477 }
3478 java.lang.ClassLoader cl = context.getClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 data.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003480 data.intent.prepareToEnterProcess();
Dianne Hackborne829fef2010-10-26 17:44:01 -07003481 data.setExtrasClassLoader(cl);
Todd Kennedy233a0b12018-01-29 20:30:24 +00003482 receiver = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003483 .instantiateReceiver(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003485 if (DEBUG_BROADCAST) Slog.i(TAG,
3486 "Finishing failed broadcast to " + data.intent.getComponent());
3487 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 throw new RuntimeException(
3489 "Unable to instantiate receiver " + component
3490 + ": " + e.toString(), e);
3491 }
3492
3493 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003494 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 TAG, "Performing receive of " + data.intent
3496 + ": app=" + app
3497 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003498 + ", pkg=" + packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 + ", comp=" + data.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003500 + ", dir=" + packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003502 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07003503 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 receiver.onReceive(context.getReceiverRestrictedContext(),
3505 data.intent);
3506 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003507 if (DEBUG_BROADCAST) Slog.i(TAG,
3508 "Finishing failed broadcast to " + data.intent.getComponent());
3509 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 if (!mInstrumentation.onException(receiver, e)) {
3511 throw new RuntimeException(
3512 "Unable to start receiver " + component
3513 + ": " + e.toString(), e);
3514 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003515 } finally {
3516 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 }
3518
Dianne Hackborne829fef2010-10-26 17:44:01 -07003519 if (receiver.getPendingResult() != null) {
3520 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 }
3522 }
3523
Christopher Tate181fafa2009-05-14 11:12:14 -07003524 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07003525 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003526 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003527
Christopher Tate346acb12012-10-15 19:20:25 -07003528 // Sanity check the requested target package's uid against ours
3529 try {
3530 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
3531 data.appInfo.packageName, 0, UserHandle.myUserId());
3532 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
3533 Slog.w(TAG, "Asked to instantiate non-matching package "
3534 + data.appInfo.packageName);
3535 return;
3536 }
3537 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003538 throw e.rethrowFromSystemServer();
Christopher Tate346acb12012-10-15 19:20:25 -07003539 }
3540
Christopher Tate181fafa2009-05-14 11:12:14 -07003541 // no longer idle; we have backup work to do
3542 unscheduleGcIdler();
3543
3544 // instantiate the BackupAgent class named in the manifest
Todd Kennedy233a0b12018-01-29 20:30:24 +00003545 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3546 String packageName = packageInfo.mPackageName;
Christopher Tate346acb12012-10-15 19:20:25 -07003547 if (packageName == null) {
3548 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
3549 return;
3550 }
3551
Christopher Tate181fafa2009-05-14 11:12:14 -07003552 String classname = data.appInfo.backupAgentName;
Christopher Tate79ec80d2011-06-24 14:58:49 -07003553 // full backup operation but no app-supplied agent? use the default implementation
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003554 if (classname == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
3555 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07003556 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07003557 }
Christopher Tate4a627c72011-04-01 14:43:32 -07003558
Christopher Tate181fafa2009-05-14 11:12:14 -07003559 try {
Christopher Tated1475e02009-07-09 15:36:17 -07003560 IBinder binder = null;
Christopher Tate2e40d112014-07-15 12:37:38 -07003561 BackupAgent agent = mBackupAgents.get(packageName);
3562 if (agent != null) {
3563 // reusing the existing instance
3564 if (DEBUG_BACKUP) {
3565 Slog.v(TAG, "Reusing existing agent instance");
Christopher Tated1475e02009-07-09 15:36:17 -07003566 }
Christopher Tate2e40d112014-07-15 12:37:38 -07003567 binder = agent.onBind();
3568 } else {
3569 try {
3570 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
3571
Todd Kennedy233a0b12018-01-29 20:30:24 +00003572 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003573 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tate2e40d112014-07-15 12:37:38 -07003574
3575 // set up the agent's context
Todd Kennedy233a0b12018-01-29 20:30:24 +00003576 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Christopher Tate2e40d112014-07-15 12:37:38 -07003577 context.setOuterContext(agent);
3578 agent.attach(context);
3579
3580 agent.onCreate();
3581 binder = agent.onBind();
3582 mBackupAgents.put(packageName, agent);
3583 } catch (Exception e) {
3584 // If this is during restore, fail silently; otherwise go
3585 // ahead and let the user see the crash.
3586 Slog.e(TAG, "Agent threw during creation: " + e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003587 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
3588 && data.backupMode !=
3589 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
Christopher Tate2e40d112014-07-15 12:37:38 -07003590 throw e;
3591 }
3592 // falling through with 'binder' still null
3593 }
Christopher Tated1475e02009-07-09 15:36:17 -07003594 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003595
3596 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07003597 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003598 ActivityManager.getService().backupAgentCreated(packageName, binder);
Christopher Tate181fafa2009-05-14 11:12:14 -07003599 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003600 throw e.rethrowFromSystemServer();
Christopher Tate181fafa2009-05-14 11:12:14 -07003601 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003602 } catch (Exception e) {
3603 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07003604 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07003605 }
3606 }
3607
3608 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07003609 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003610 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07003611
Todd Kennedy233a0b12018-01-29 20:30:24 +00003612 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3613 String packageName = packageInfo.mPackageName;
Christopher Tate181fafa2009-05-14 11:12:14 -07003614 BackupAgent agent = mBackupAgents.get(packageName);
3615 if (agent != null) {
3616 try {
3617 agent.onDestroy();
3618 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003619 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07003620 e.printStackTrace();
3621 }
3622 mBackupAgents.remove(packageName);
3623 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003624 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003625 }
3626 }
3627
Mathew Inwood4fb17d12018-08-14 14:25:44 +01003628 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07003629 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 // If we are getting ready to gc after going to the background, well
3631 // we are back active so skip it.
3632 unscheduleGcIdler();
3633
Todd Kennedy233a0b12018-01-29 20:30:24 +00003634 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003635 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 Service service = null;
3637 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003638 java.lang.ClassLoader cl = packageInfo.getClassLoader();
3639 service = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003640 .instantiateService(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 } catch (Exception e) {
3642 if (!mInstrumentation.onException(service, e)) {
3643 throw new RuntimeException(
3644 "Unable to instantiate service " + data.info.name
3645 + ": " + e.toString(), e);
3646 }
3647 }
3648
3649 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003650 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651
Todd Kennedy233a0b12018-01-29 20:30:24 +00003652 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Jeff Browndefd4a62014-03-10 21:24:37 -07003653 context.setOuterContext(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654
Todd Kennedy233a0b12018-01-29 20:30:24 +00003655 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 service.attach(context, this, data.info.name, data.token, app,
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003657 ActivityManager.getService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 service.onCreate();
3659 mServices.put(data.token, service);
3660 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003661 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003662 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003664 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 }
3666 } catch (Exception e) {
3667 if (!mInstrumentation.onException(service, e)) {
3668 throw new RuntimeException(
3669 "Unable to create service " + data.info.name
3670 + ": " + e.toString(), e);
3671 }
3672 }
3673 }
3674
Romain Guy65b345f2011-07-27 18:51:50 -07003675 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07003677 if (DEBUG_SERVICE)
3678 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 if (s != null) {
3680 try {
3681 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003682 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 try {
3684 if (!data.rebind) {
3685 IBinder binder = s.onBind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003686 ActivityManager.getService().publishService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 data.token, data.intent, binder);
3688 } else {
3689 s.onRebind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003690 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003691 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003693 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003695 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 }
3697 } catch (Exception e) {
3698 if (!mInstrumentation.onException(s, e)) {
3699 throw new RuntimeException(
3700 "Unable to bind to service " + s
3701 + " with " + data.intent + ": " + e.toString(), e);
3702 }
3703 }
3704 }
3705 }
3706
Romain Guy65b345f2011-07-27 18:51:50 -07003707 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 Service s = mServices.get(data.token);
3709 if (s != null) {
3710 try {
3711 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003712 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 boolean doRebind = s.onUnbind(data.intent);
3714 try {
3715 if (doRebind) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003716 ActivityManager.getService().unbindFinished(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 data.token, data.intent, doRebind);
3718 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003719 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003720 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 }
3722 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003723 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 }
3725 } catch (Exception e) {
3726 if (!mInstrumentation.onException(s, e)) {
3727 throw new RuntimeException(
3728 "Unable to unbind to service " + s
3729 + " with " + data.intent + ": " + e.toString(), e);
3730 }
3731 }
3732 }
3733 }
3734
Dianne Hackborn625ac272010-09-17 18:29:22 -07003735 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003736 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3737 try {
3738 Service s = mServices.get(info.token);
3739 if (s != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003740 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3741 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003742 s.dump(info.fd.getFileDescriptor(), pw, info.args);
3743 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003745 } finally {
3746 IoUtils.closeQuietly(info.fd);
3747 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 }
3749 }
3750
Dianne Hackborn625ac272010-09-17 18:29:22 -07003751 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003752 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3753 try {
3754 ActivityClientRecord r = mActivities.get(info.token);
3755 if (r != null && r.activity != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003756 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3757 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003758 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
3759 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07003760 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003761 } finally {
3762 IoUtils.closeQuietly(info.fd);
3763 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07003764 }
3765 }
3766
Marco Nelissen18cb2872011-11-15 11:19:53 -08003767 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003768 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3769 try {
3770 ProviderClientRecord r = mLocalProviders.get(info.token);
3771 if (r != null && r.mLocalProvider != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003772 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3773 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003774 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
3775 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08003776 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003777 } finally {
3778 IoUtils.closeQuietly(info.fd);
3779 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08003780 }
3781 }
3782
Romain Guy65b345f2011-07-27 18:51:50 -07003783 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 Service s = mServices.get(data.token);
3785 if (s != null) {
3786 try {
3787 if (data.args != null) {
3788 data.args.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003789 data.args.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003791 int res;
3792 if (!data.taskRemoved) {
3793 res = s.onStartCommand(data.args, data.flags, data.startId);
3794 } else {
3795 s.onTaskRemoved(data.args);
3796 res = Service.START_TASK_REMOVED_COMPLETE;
3797 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003798
3799 QueuedWork.waitToFinish();
3800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003802 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003803 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003805 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003806 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003807 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 } catch (Exception e) {
3809 if (!mInstrumentation.onException(s, e)) {
3810 throw new RuntimeException(
3811 "Unable to start service " + s
3812 + " with " + data.args + ": " + e.toString(), e);
3813 }
3814 }
3815 }
3816 }
3817
Romain Guy65b345f2011-07-27 18:51:50 -07003818 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819 Service s = mServices.remove(token);
3820 if (s != null) {
3821 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003822 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 s.onDestroy();
Amith Yamasani75928252017-05-22 15:10:47 -07003824 s.detachAndCleanUp();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003826 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08003828 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003830
3831 QueuedWork.waitToFinish();
3832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003834 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003835 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003837 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 }
3839 } catch (Exception e) {
3840 if (!mInstrumentation.onException(s, e)) {
3841 throw new RuntimeException(
3842 "Unable to stop service " + s
3843 + ": " + e.toString(), e);
3844 }
Craig Mautner66c4a822015-01-16 12:48:16 -08003845 Slog.i(TAG, "handleStopService: exception for " + token, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 }
Craig Mautner9776ad42015-01-15 14:38:39 -08003847 } else {
3848 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003850 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 }
3852
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003853 /**
3854 * Resume the activity.
3855 * @param token Target activity token.
3856 * @param finalStateRequest Flag indicating if this is part of final state resolution for a
3857 * transaction.
3858 * @param reason Reason for performing the action.
3859 *
3860 * @return The {@link ActivityClientRecord} that was resumed, {@code null} otherwise.
3861 */
3862 @VisibleForTesting
3863 public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
Andrii Kuliandfbf9712018-03-08 15:42:24 -08003864 String reason) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003865 final ActivityClientRecord r = mActivities.get(token);
3866 if (localLOGV) {
3867 Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
3868 }
3869 if (r == null || r.activity.mFinished) {
3870 return null;
3871 }
3872 if (r.getLifecycleState() == ON_RESUME) {
3873 if (!finalStateRequest) {
3874 final RuntimeException e = new IllegalStateException(
3875 "Trying to resume activity which is already resumed");
3876 Slog.e(TAG, e.getMessage(), e);
3877 Slog.e(TAG, r.getStateString());
3878 // TODO(lifecycler): A double resume request is possible when an activity
3879 // receives two consequent transactions with relaunch requests and "resumed"
3880 // final state requests and the second relaunch is omitted. We still try to
3881 // handle two resume requests for the final state. For cases other than this
3882 // one, we don't expect it to happen.
Andrii Kulian9956d892018-02-14 13:48:56 -08003883 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003884 return null;
3885 }
3886 if (finalStateRequest) {
3887 r.hideForNow = false;
3888 r.activity.mStartedActivity = false;
3889 }
3890 try {
3891 r.activity.onStateNotSaved();
3892 r.activity.mFragments.noteStateNotSaved();
3893 checkAndBlockForNetworkAccess();
3894 if (r.pendingIntents != null) {
3895 deliverNewIntents(r, r.pendingIntents);
3896 r.pendingIntents = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003898 if (r.pendingResults != null) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07003899 deliverResults(r, r.pendingResults, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003900 r.pendingResults = null;
3901 }
3902 r.activity.performResume(r.startsNotResumed, reason);
Bob Leee5408332009-09-04 18:31:17 -07003903
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003904 r.state = null;
3905 r.persistentState = null;
3906 r.setState(ON_RESUME);
3907 } catch (Exception e) {
3908 if (!mInstrumentation.onException(r.activity, e)) {
3909 throw new RuntimeException("Unable to resume activity "
3910 + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 }
3912 }
3913 return r;
3914 }
3915
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003916 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
3917 if (r.mPreserveWindow && !force) {
3918 return;
3919 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003920 if (r.mPendingRemoveWindow != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003921 r.mPendingRemoveWindowManager.removeViewImmediate(
3922 r.mPendingRemoveWindow.getDecorView());
3923 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003924 if (wtoken != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07003925 WindowManagerGlobal.getInstance().closeAll(wtoken,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003926 r.activity.getClass().getName(), "Activity");
3927 }
3928 }
3929 r.mPendingRemoveWindow = null;
3930 r.mPendingRemoveWindowManager = null;
3931 }
3932
Andrii Kulian446e8242017-10-26 15:17:29 -07003933 @Override
Andrii Kuliandfbf9712018-03-08 15:42:24 -08003934 public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003935 String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 // If we are getting ready to gc after going to the background, well
3937 // we are back active so skip it.
3938 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003939 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940
Adam Powellcfbe9be2013-11-06 14:58:58 -08003941 // TODO Push resumeArgs into the activity for consideration
Andrii Kuliandfbf9712018-03-08 15:42:24 -08003942 final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003943 if (r == null) {
3944 // We didn't actually resume the activity, so skipping any follow-up actions.
3945 return;
3946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003948 final Activity a = r.activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003950 if (localLOGV) {
3951 Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
3952 + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
3953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003955 final int forwardBit = isForward
3956 ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07003957
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003958 // If the window hasn't yet been added to the window manager,
3959 // and this guy didn't finish itself or start another activity,
3960 // then go ahead and add the window.
3961 boolean willBeVisible = !a.mStartedActivity;
3962 if (!willBeVisible) {
3963 try {
3964 willBeVisible = ActivityManager.getService().willActivityBeVisible(
3965 a.getActivityToken());
3966 } catch (RemoteException e) {
3967 throw e.rethrowFromSystemServer();
3968 }
3969 }
3970 if (r.window == null && !a.mFinished && willBeVisible) {
3971 r.window = r.activity.getWindow();
3972 View decor = r.window.getDecorView();
3973 decor.setVisibility(View.INVISIBLE);
3974 ViewManager wm = a.getWindowManager();
3975 WindowManager.LayoutParams l = r.window.getAttributes();
3976 a.mDecor = decor;
3977 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
3978 l.softInputMode |= forwardBit;
3979 if (r.mPreserveWindow) {
3980 a.mWindowAdded = true;
3981 r.mPreserveWindow = false;
3982 // Normally the ViewRoot sets up callbacks with the Activity
3983 // in addView->ViewRootImpl#setView. If we are instead reusing
3984 // the decor view we have to notify the view root that the
3985 // callbacks may have changed.
3986 ViewRootImpl impl = decor.getViewRootImpl();
3987 if (impl != null) {
3988 impl.notifyChildRebuilt();
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003989 }
3990 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003991 if (a.mVisibleFromClient) {
3992 if (!a.mWindowAdded) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003993 a.mWindowAdded = true;
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003994 wm.addView(decor, l);
3995 } else {
3996 // The activity will get a callback for this {@link LayoutParams} change
3997 // earlier. However, at that time the decor will not be set (this is set
3998 // in this method), so no action will be taken. This call ensures the
3999 // callback occurs with the decor set.
4000 a.onWindowAttributesChanged(l);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004001 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003
4004 // If the window has already been added, but during resume
4005 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004006 // window visible.
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004007 } else if (!willBeVisible) {
4008 if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
4009 r.hideForNow = true;
4010 }
4011
4012 // Get rid of anything left hanging around.
4013 cleanUpPendingRemoveWindows(r, false /* force */);
4014
4015 // The window is now visible if it has been added, we are not
4016 // simply finishing, and we are not starting another activity.
4017 if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
4018 if (r.newConfig != null) {
4019 performConfigurationChangedForActivity(r, r.newConfig);
4020 if (DEBUG_CONFIGURATION) {
4021 Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
4022 + r.activity.mCurrentConfig);
4023 }
4024 r.newConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004026 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
4027 WindowManager.LayoutParams l = r.window.getAttributes();
4028 if ((l.softInputMode
4029 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
4030 != forwardBit) {
4031 l.softInputMode = (l.softInputMode
4032 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
4033 | forwardBit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 if (r.activity.mVisibleFromClient) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004035 ViewManager wm = a.getWindowManager();
4036 View decor = r.window.getDecorView();
4037 wm.updateViewLayout(decor, l);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 }
4039 }
4040
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004041 r.activity.mVisibleFromServer = true;
4042 mNumVisibleActivities++;
4043 if (r.activity.mVisibleFromClient) {
4044 r.activity.makeVisible();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 }
4046 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004047
4048 r.nextIdle = mNewActivities;
4049 mNewActivities = r;
4050 if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
4051 Looper.myQueue().addIdleHandler(new Idler());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 }
4053
Andrii Kulian446e8242017-10-26 15:17:29 -07004054 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004055 public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
Andrii Kuliana6176e32018-02-27 11:51:18 -08004056 int configChanges, PendingTransactionActions pendingActions, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004057 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 if (userLeaving) {
4060 performUserLeavingActivity(r);
4061 }
Bob Leee5408332009-09-04 18:31:17 -07004062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 r.activity.mConfigChangeFlags |= configChanges;
Andrii Kuliand25680c2018-02-21 15:16:58 -08004064 performPauseActivity(r, finished, reason, pendingActions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07004066 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004067 if (r.isPreHoneycomb()) {
4068 QueuedWork.waitToFinish();
4069 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004070 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 }
4072 }
4073
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004074 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 mInstrumentation.callActivityOnUserLeaving(r.activity);
4076 }
4077
Andrii Kulian8ae79572018-01-26 15:36:06 -08004078 final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
4079 PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004080 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004081 return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 }
4083
Andrii Kulian8ae79572018-01-26 15:36:06 -08004084 /**
4085 * Pause the activity.
4086 * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
4087 */
4088 private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
4089 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 if (r.paused) {
4091 if (r.activity.mFinished) {
4092 // If we are finishing, we won't call onResume() in certain cases.
4093 // So here we likewise don't want to call onPause() if the activity
4094 // isn't resumed.
4095 return null;
4096 }
4097 RuntimeException e = new RuntimeException(
4098 "Performing pause of activity that is not resumed: "
4099 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004100 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 if (finished) {
4103 r.activity.mFinished = true;
4104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105
Andrii Kulian8ae79572018-01-26 15:36:06 -08004106 // Pre-Honeycomb apps always save their state before pausing
4107 final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
4108 if (shouldSaveState) {
4109 callActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004111
4112 performPauseActivityIfNeeded(r, reason);
Jeff Hamilton52d32032011-01-08 15:31:26 -06004113
4114 // Notify any outstanding on paused listeners
4115 ArrayList<OnActivityPausedListener> listeners;
4116 synchronized (mOnPauseListeners) {
4117 listeners = mOnPauseListeners.remove(r.activity);
4118 }
4119 int size = (listeners != null ? listeners.size() : 0);
4120 for (int i = 0; i < size; i++) {
4121 listeners.get(i).onPaused(r.activity);
4122 }
4123
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004124 final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
4125 if (oldState != null) {
4126 // We need to keep around the original state, in case we need to be created again.
4127 // But we only do this for pre-Honeycomb apps, which always save their state when
4128 // pausing, so we can not have them save their state when restarting from a paused
4129 // state. For HC and later, we want to (and can) let the state be saved as the
4130 // normal part of stopping the activity.
4131 if (r.isPreHoneycomb()) {
4132 r.state = oldState;
4133 }
4134 }
4135
Andrii Kulian8ae79572018-01-26 15:36:06 -08004136 return shouldSaveState ? r.state : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 }
4138
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004139 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4140 if (r.paused) {
4141 // You are already paused silly...
4142 return;
4143 }
4144
4145 try {
4146 r.activity.mCalled = false;
4147 mInstrumentation.callActivityOnPause(r.activity);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004148 if (!r.activity.mCalled) {
4149 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4150 + " did not call through to super.onPause()");
4151 }
4152 } catch (SuperNotCalledException e) {
4153 throw e;
4154 } catch (Exception e) {
4155 if (!mInstrumentation.onException(r.activity, e)) {
4156 throw new RuntimeException("Unable to pause activity "
4157 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4158 }
4159 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004160 r.setState(ON_PAUSE);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004161 }
4162
Andrii Kulian829829c2018-03-19 18:19:05 -07004163 /** Called from {@link LocalActivityManager}. */
Mathew Inwood4fb17d12018-08-14 14:25:44 +01004164 @UnsupportedAppUsage
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004165 final void performStopActivity(IBinder token, boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004166 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian829829c2018-03-19 18:19:05 -07004167 performStopActivityInner(r, null /* stopInfo */, false /* keepShown */, saveState,
4168 false /* finalStateRequest */, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004171 private static final class ProviderRefCount {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004172 public final ContentProviderHolder holder;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004173 public final ProviderClientRecord client;
4174 public int stableCount;
4175 public int unstableCount;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004176
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004177 // When this is set, the stable and unstable ref counts are 0 and
4178 // we have a pending operation scheduled to remove the ref count
4179 // from the activity manager. On the activity manager we are still
4180 // holding an unstable ref, though it is not reflected in the counts
4181 // here.
4182 public boolean removePending;
4183
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004184 ProviderRefCount(ContentProviderHolder inHolder,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004185 ProviderClientRecord inClient, int sCount, int uCount) {
4186 holder = inHolder;
4187 client = inClient;
4188 stableCount = sCount;
4189 unstableCount = uCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 }
4191 }
4192
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004193 /**
4194 * Core implementation of stopping an activity. Note this is a little
4195 * tricky because the server's meaning of stop is slightly different
4196 * than our client -- for the server, stop means to save state and give
4197 * it the result when it is done, but the window may still be visible.
4198 * For the client, we want to call onStop()/onStart() to indicate when
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004199 * the activity's UI visibility changes.
Andrii Kulian829829c2018-03-19 18:19:05 -07004200 * @param r Target activity client record.
4201 * @param info Action that will report activity stop to server.
4202 * @param keepShown Flag indicating whether the activity is still shown.
4203 * @param saveState Flag indicating whether the activity state should be saved.
4204 * @param finalStateRequest Flag indicating if this call is handling final lifecycle state
4205 * request for a transaction.
4206 * @param reason Reason for performing this operation.
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004207 */
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004208 private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
Andrii Kulian829829c2018-03-19 18:19:05 -07004209 boolean saveState, boolean finalStateRequest, String reason) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004210 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 if (r != null) {
4212 if (!keepShown && r.stopped) {
4213 if (r.activity.mFinished) {
4214 // If we are finishing, we won't call onResume() in certain
4215 // cases. So here we likewise don't want to call onStop()
4216 // if the activity isn't resumed.
4217 return;
4218 }
Andrii Kulian829829c2018-03-19 18:19:05 -07004219 if (!finalStateRequest) {
4220 final RuntimeException e = new RuntimeException(
4221 "Performing stop of activity that is already stopped: "
4222 + r.intent.getComponent().toShortString());
4223 Slog.e(TAG, e.getMessage(), e);
4224 Slog.e(TAG, r.getStateString());
4225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004226 }
4227
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004228 // One must first be paused before stopped...
4229 performPauseActivityIfNeeded(r, reason);
4230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 if (info != null) {
4232 try {
4233 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07004234 // For now, don't create the thumbnail here; we are
4235 // doing that by doing a screen snapshot.
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004236 info.setDescription(r.activity.onCreateDescription());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 } catch (Exception e) {
4238 if (!mInstrumentation.onException(r.activity, e)) {
4239 throw new RuntimeException(
4240 "Unable to save state of activity "
4241 + r.intent.getComponent().toShortString()
4242 + ": " + e.toString(), e);
4243 }
4244 }
4245 }
4246
4247 if (!keepShown) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004248 callActivityOnStop(r, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
4251 }
4252
Andrii Kulian8ae79572018-01-26 15:36:06 -08004253 /**
4254 * Calls {@link Activity#onStop()} and {@link Activity#onSaveInstanceState(Bundle)}, and updates
4255 * the client record's state.
4256 * All calls to stop an activity must be done through this method to make sure that
4257 * {@link Activity#onSaveInstanceState(Bundle)} is also executed in the same call.
4258 */
4259 private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
Andrii Kulian391161f2018-01-29 10:50:02 -08004260 // Before P onSaveInstanceState was called before onStop, starting with P it's
4261 // called after. Before Honeycomb state was always saved before onPause.
Andrii Kulian8ae79572018-01-26 15:36:06 -08004262 final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
4263 && !r.isPreHoneycomb();
Andrii Kulian391161f2018-01-29 10:50:02 -08004264 final boolean isPreP = r.isPreP();
4265 if (shouldSaveState && isPreP) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004266 callActivityOnSaveInstanceState(r);
4267 }
4268
4269 try {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004270 r.activity.performStop(false /*preserveWindow*/, reason);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004271 } catch (SuperNotCalledException e) {
4272 throw e;
4273 } catch (Exception e) {
4274 if (!mInstrumentation.onException(r.activity, e)) {
4275 throw new RuntimeException(
4276 "Unable to stop activity "
4277 + r.intent.getComponent().toShortString()
4278 + ": " + e.toString(), e);
4279 }
4280 }
4281 r.setState(ON_STOP);
Andrii Kulian391161f2018-01-29 10:50:02 -08004282
4283 if (shouldSaveState && !isPreP) {
4284 callActivityOnSaveInstanceState(r);
4285 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004286 }
4287
Romain Guy65b345f2011-07-27 18:51:50 -07004288 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 View v = r.activity.mDecor;
4290 if (v != null) {
4291 if (show) {
4292 if (!r.activity.mVisibleFromServer) {
4293 r.activity.mVisibleFromServer = true;
4294 mNumVisibleActivities++;
4295 if (r.activity.mVisibleFromClient) {
4296 r.activity.makeVisible();
4297 }
4298 }
4299 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004300 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004301 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Adam Lesinski082614c2016-03-04 14:33:47 -08004302 + r.activityInfo.name + " with new config "
4303 + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 r.newConfig = null;
4305 }
4306 } else {
4307 if (r.activity.mVisibleFromServer) {
4308 r.activity.mVisibleFromServer = false;
4309 mNumVisibleActivities--;
4310 v.setVisibility(View.INVISIBLE);
4311 }
4312 }
4313 }
4314 }
4315
Andrii Kulian446e8242017-10-26 15:17:29 -07004316 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004317 public void handleStopActivity(IBinder token, boolean show, int configChanges,
Andrii Kulian829829c2018-03-19 18:19:05 -07004318 PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004319 final ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 r.activity.mConfigChangeFlags |= configChanges;
4321
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004322 final StopInfo stopInfo = new StopInfo();
Andrii Kulian829829c2018-03-19 18:19:05 -07004323 performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
4324 reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004326 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 TAG, "Finishing stop of " + r + ": show=" + show
4328 + " win=" + r.window);
4329
4330 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07004331
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004332 // Make sure any pending writes are now committed.
4333 if (!r.isPreHoneycomb()) {
4334 QueuedWork.waitToFinish();
4335 }
4336
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004337 stopInfo.setActivity(r);
4338 stopInfo.setState(r.state);
4339 stopInfo.setPersistentState(r.persistentState);
4340 pendingActions.setStopInfo(stopInfo);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004341 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 }
4343
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004344 /**
4345 * Schedule the call to tell the activity manager we have stopped. We don't do this
4346 * immediately, because we want to have a chance for any other pending work (in particular
4347 * memory trim requests) to complete before you tell the activity manager to proceed and allow
4348 * us to go fully into the background.
4349 */
4350 @Override
4351 public void reportStop(PendingTransactionActions pendingActions) {
4352 mH.post(pendingActions.getStopInfo());
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004353 }
4354
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004355 @Override
4356 public void performRestartActivity(IBinder token, boolean start) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004357 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 if (r.stopped) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004359 r.activity.performRestart(start, "performRestartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004360 if (start) {
4361 r.setState(ON_START);
4362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363 }
4364 }
4365
Andrii Kulian446e8242017-10-26 15:17:29 -07004366 @Override
4367 public void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004368 ActivityClientRecord r = mActivities.get(token);
Tim Murraye1e6c662015-04-07 13:24:14 -07004369
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08004370 if (r == null) {
4371 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
4372 return;
4373 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 if (!show && !r.stopped) {
Andrii Kulian829829c2018-03-19 18:19:05 -07004376 performStopActivityInner(r, null /* stopInfo */, show, false /* saveState */,
4377 false /* finalStateRequest */, "handleWindowVisibility");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 } else if (show && r.stopped) {
4379 // If we are getting ready to gc after going to the background, well
4380 // we are back active so skip it.
4381 unscheduleGcIdler();
4382
Andrii Kuliand25680c2018-02-21 15:16:58 -08004383 r.activity.performRestart(true /* start */, "handleWindowVisibility");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004384 r.setState(ON_START);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004385 }
4386 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07004387 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 TAG, "Handle window " + r + " visibility: " + show);
4389 updateVisibility(r, show);
4390 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004391 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 }
4393
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004394 // TODO: This method should be changed to use {@link #performStopActivityInner} to perform to
4395 // stop operation on the activity to reduce code duplication and the chance of fixing a bug in
4396 // one place and missing the other.
Romain Guy65b345f2011-07-27 18:51:50 -07004397 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004398 ActivityClientRecord r = mActivities.get(token);
4399
4400 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004401 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004402 return;
4403 }
4404
4405 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004406 if (!r.stopped && !r.isPreHoneycomb()) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004407 callActivityOnStop(r, true /* saveState */, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004408 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004409
4410 // Make sure any pending writes are now committed.
4411 if (!r.isPreHoneycomb()) {
4412 QueuedWork.waitToFinish();
4413 }
4414
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004415 // Tell activity manager we slept.
4416 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004417 ActivityManager.getService().activitySlept(r.token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004418 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004419 throw ex.rethrowFromSystemServer();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004420 }
4421 } else {
4422 if (r.stopped && r.activity.mVisibleFromServer) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004423 r.activity.performRestart(true /* start */, "handleSleeping");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004424 r.setState(ON_START);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004425 }
4426 }
4427 }
4428
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004429 private void handleSetCoreSettings(Bundle coreSettings) {
Craig Mautner88c05892013-06-28 09:47:45 -07004430 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004431 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004432 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004433 onCoreSettingsChange();
4434 }
4435
4436 private void onCoreSettingsChange() {
4437 boolean debugViewAttributes =
4438 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
4439 if (debugViewAttributes != View.mDebugViewAttributes) {
4440 View.mDebugViewAttributes = debugViewAttributes;
4441
4442 // request all activities to relaunch for the changes to take place
Wale Ogunwale5527a502018-02-20 18:18:21 -08004443 relaunchAllActivities();
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004444 }
4445 }
4446
Wale Ogunwale5527a502018-02-20 18:18:21 -08004447 private void relaunchAllActivities() {
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004448 for (Map.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
4449 final Activity activity = entry.getValue().activity;
4450 if (!activity.mFinished) {
Andrii Kulian320e3b52018-05-03 16:26:25 -07004451 scheduleRelaunchActivity(entry.getKey());
Jon Miranda836c0a82014-08-11 12:32:26 -07004452 }
4453 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004454 }
4455
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004456 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00004457 LoadedApk apk = peekPackageInfo(data.pkg, false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004458 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004459 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004460 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00004461 apk = peekPackageInfo(data.pkg, true);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004462 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004463 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004464 }
4465 handleConfigurationChanged(mConfiguration, data.info);
Jeff Brown98365d72012-08-19 20:30:52 -07004466 WindowManagerGlobal.getInstance().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004467 }
4468
Andrii Kuliane55b0092018-04-19 15:29:22 -07004469 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 final int N = results.size();
4471 for (int i=0; i<N; i++) {
4472 ResultInfo ri = results.get(i);
4473 try {
4474 if (ri.mData != null) {
4475 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004476 ri.mData.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004478 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07004479 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 r.activity.dispatchActivityResult(ri.mResultWho,
Andrii Kuliane55b0092018-04-19 15:29:22 -07004481 ri.mRequestCode, ri.mResultCode, ri.mData, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 } catch (Exception e) {
4483 if (!mInstrumentation.onException(r.activity, e)) {
4484 throw new RuntimeException(
4485 "Failure delivering result " + ri + " to activity "
4486 + r.intent.getComponent().toShortString()
4487 + ": " + e.toString(), e);
4488 }
4489 }
4490 }
4491 }
4492
Andrii Kulian446e8242017-10-26 15:17:29 -07004493 @Override
Andrii Kuliane55b0092018-04-19 15:29:22 -07004494 public void handleSendResult(IBinder token, List<ResultInfo> results, String reason) {
Andrii Kulian446e8242017-10-26 15:17:29 -07004495 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004496 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 if (r != null) {
4498 final boolean resumed = !r.paused;
4499 if (!r.activity.mFinished && r.activity.mDecor != null
4500 && r.hideForNow && resumed) {
4501 // We had hidden the activity because it started another
4502 // one... we have gotten a result back and we are not
4503 // paused, so make sure our window is visible.
4504 updateVisibility(r, true);
4505 }
4506 if (resumed) {
4507 try {
4508 // Now we are idle.
4509 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004510 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 mInstrumentation.callActivityOnPause(r.activity);
4512 if (!r.activity.mCalled) {
4513 throw new SuperNotCalledException(
4514 "Activity " + r.intent.getComponent().toShortString()
4515 + " did not call through to super.onPause()");
4516 }
4517 } catch (SuperNotCalledException e) {
4518 throw e;
4519 } catch (Exception e) {
4520 if (!mInstrumentation.onException(r.activity, e)) {
4521 throw new RuntimeException(
4522 "Unable to pause activity "
4523 + r.intent.getComponent().toShortString()
4524 + ": " + e.toString(), e);
4525 }
4526 }
4527 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07004528 checkAndBlockForNetworkAccess();
Andrii Kuliane55b0092018-04-19 15:29:22 -07004529 deliverResults(r, results, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 if (resumed) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07004531 r.activity.performResume(false, reason);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004532 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 }
4534 }
4535 }
4536
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004537 /** Core implementation of activity destroy call. */
4538 ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004539 int configChanges, boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004540 ActivityClientRecord r = mActivities.get(token);
Craig Mautner88c05892013-06-28 09:47:45 -07004541 Class<? extends Activity> activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004542 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004544 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 r.activity.mConfigChangeFlags |= configChanges;
4546 if (finishing) {
4547 r.activity.mFinished = true;
4548 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004549
4550 performPauseActivityIfNeeded(r, "destroy");
4551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 if (!r.stopped) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004553 callActivityOnStop(r, false /* saveState */, "destroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004554 }
4555 if (getNonConfigInstance) {
4556 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004557 r.lastNonConfigurationInstances
4558 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559 } catch (Exception e) {
4560 if (!mInstrumentation.onException(r.activity, e)) {
4561 throw new RuntimeException(
4562 "Unable to retain activity "
4563 + r.intent.getComponent().toShortString()
4564 + ": " + e.toString(), e);
4565 }
4566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567 }
4568 try {
4569 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004570 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004571 if (!r.activity.mCalled) {
4572 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004573 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 " did not call through to super.onDestroy()");
4575 }
4576 if (r.window != null) {
4577 r.window.closeAllPanels();
4578 }
4579 } catch (SuperNotCalledException e) {
4580 throw e;
4581 } catch (Exception e) {
4582 if (!mInstrumentation.onException(r.activity, e)) {
4583 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004584 "Unable to destroy activity " + safeToComponentShortString(r.intent)
4585 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 }
4587 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004588 r.setState(ON_DESTROY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 }
Tim Murray12f511e2018-10-22 15:26:08 -07004590 schedulePurgeIdler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004592 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 return r;
4594 }
4595
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004596 private static String safeToComponentShortString(Intent intent) {
4597 ComponentName component = intent.getComponent();
4598 return component == null ? "[Unknown]" : component.toShortString();
4599 }
4600
Andrii Kulian446e8242017-10-26 15:17:29 -07004601 @Override
4602 public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
Bryce Leea33c13d2018-02-08 14:37:06 -08004603 boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004604 ActivityClientRecord r = performDestroyActivity(token, finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004605 configChanges, getNonConfigInstance, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606 if (r != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004607 cleanUpPendingRemoveWindows(r, finishing);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 WindowManager wm = r.activity.getWindowManager();
4609 View v = r.activity.mDecor;
4610 if (v != null) {
4611 if (r.activity.mVisibleFromServer) {
4612 mNumVisibleActivities--;
4613 }
4614 IBinder wtoken = v.getWindowToken();
4615 if (r.activity.mWindowAdded) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004616 if (r.mPreserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004617 // Hold off on removing this until the new activity's
4618 // window is being added.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004619 r.mPendingRemoveWindow = r.window;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004620 r.mPendingRemoveWindowManager = wm;
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004621 // We can only keep the part of the view hierarchy that we control,
4622 // everything else must be removed, because it might not be able to
4623 // behave properly when activity is relaunching.
4624 r.window.clearContentView();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004625 } else {
4626 wm.removeViewImmediate(v);
4627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004629 if (wtoken != null && r.mPendingRemoveWindow == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004630 WindowManagerGlobal.getInstance().closeAll(wtoken,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 r.activity.getClass().getName(), "Activity");
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004632 } else if (r.mPendingRemoveWindow != null) {
4633 // We're preserving only one window, others should be closed so app views
4634 // will be detached before the final tear down. It should be done now because
4635 // some components (e.g. WebView) rely on detach callbacks to perform receiver
4636 // unregister and other cleanup.
4637 WindowManagerGlobal.getInstance().closeAllExceptView(token, v,
4638 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 }
4640 r.activity.mDecor = null;
4641 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004642 if (r.mPendingRemoveWindow == null) {
4643 // If we are delaying the removal of the activity window, then
4644 // we can't clean up all windows here. Note that we can't do
4645 // so later either, which means any windows that aren't closed
4646 // by the app will leak. Well we try to warning them a lot
4647 // about leaking windows, because that is a bug, so if they are
4648 // using this recreate facility then they get to live with leaks.
Jeff Brown98365d72012-08-19 20:30:52 -07004649 WindowManagerGlobal.getInstance().closeAll(token,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004650 r.activity.getClass().getName(), "Activity");
4651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652
4653 // Mocked out contexts won't be participating in the normal
4654 // process lifecycle, but if we're running with a proper
4655 // ApplicationContext we need to have it tear down things
4656 // cleanly.
4657 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08004658 if (c instanceof ContextImpl) {
4659 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 r.activity.getClass().getName(), "Activity");
4661 }
4662 }
4663 if (finishing) {
4664 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004665 ActivityManager.getService().activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004666 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004667 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004668 }
4669 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004670 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 }
4672
Andrii Kulianb372da62018-01-18 10:46:24 -08004673 @Override
4674 public ActivityClientRecord prepareRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -08004675 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Andrii Kulianb372da62018-01-18 10:46:24 -08004676 int configChanges, MergedConfiguration config, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004677 ActivityClientRecord target = null;
Andrii Kulianb372da62018-01-18 10:46:24 -08004678 boolean scheduleRelaunch = false;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004679
Craig Mautner88c05892013-06-28 09:47:45 -07004680 synchronized (mResourcesManager) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004681 for (int i=0; i<mRelaunchingActivities.size(); i++) {
4682 ActivityClientRecord r = mRelaunchingActivities.get(i);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004683 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004684 if (r.token == token) {
4685 target = r;
4686 if (pendingResults != null) {
4687 if (r.pendingResults != null) {
4688 r.pendingResults.addAll(pendingResults);
4689 } else {
4690 r.pendingResults = pendingResults;
4691 }
4692 }
4693 if (pendingNewIntents != null) {
4694 if (r.pendingIntents != null) {
4695 r.pendingIntents.addAll(pendingNewIntents);
4696 } else {
4697 r.pendingIntents = pendingNewIntents;
4698 }
4699 }
4700 break;
4701 }
4702 }
4703
4704 if (target == null) {
Andrii Kulianb372da62018-01-18 10:46:24 -08004705 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null");
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004706 target = new ActivityClientRecord();
4707 target.token = token;
4708 target.pendingResults = pendingResults;
4709 target.pendingIntents = pendingNewIntents;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004710 target.mPreserveWindow = preserveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004711 mRelaunchingActivities.add(target);
Andrii Kulianb372da62018-01-18 10:46:24 -08004712 scheduleRelaunch = true;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004713 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004714 target.createdConfig = config.getGlobalConfiguration();
4715 target.overrideConfig = config.getOverrideConfiguration();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004716 target.pendingConfigChanges |= configChanges;
4717 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004718
4719 return scheduleRelaunch ? target : null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004720 }
4721
Andrii Kulianb372da62018-01-18 10:46:24 -08004722 @Override
4723 public void handleRelaunchActivity(ActivityClientRecord tmp,
4724 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004725 // If we are getting ready to gc after going to the background, well
4726 // we are back active so skip it.
4727 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004728 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729
4730 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004731 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07004732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 // First: make sure we have the most recent configuration and most
4734 // recent version of the activity, or skip it if some previous call
4735 // had taken a more recent version.
Craig Mautner88c05892013-06-28 09:47:45 -07004736 synchronized (mResourcesManager) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 int N = mRelaunchingActivities.size();
4738 IBinder token = tmp.token;
4739 tmp = null;
4740 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004741 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 if (r.token == token) {
4743 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004744 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 mRelaunchingActivities.remove(i);
4746 i--;
4747 N--;
4748 }
4749 }
Bob Leee5408332009-09-04 18:31:17 -07004750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004752 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 return;
4754 }
Bob Leee5408332009-09-04 18:31:17 -07004755
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004756 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
4757 + tmp.token + " with configChanges=0x"
4758 + Integer.toHexString(configChanges));
4759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 if (mPendingConfiguration != null) {
4761 changedConfig = mPendingConfiguration;
4762 mPendingConfiguration = null;
4763 }
4764 }
Bob Leee5408332009-09-04 18:31:17 -07004765
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004766 if (tmp.createdConfig != null) {
4767 // If the activity manager is passing us its current config,
4768 // assume that is really what we want regardless of what we
4769 // may have pending.
4770 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004771 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
4772 && mConfiguration.diff(tmp.createdConfig) != 0)) {
4773 if (changedConfig == null
4774 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
4775 changedConfig = tmp.createdConfig;
4776 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004777 }
4778 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004779
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004780 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004781 + tmp.token + ": changedConfig=" + changedConfig);
Tim Murraye1e6c662015-04-07 13:24:14 -07004782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 // If there was a pending configuration change, execute it first.
4784 if (changedConfig != null) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -07004785 mCurDefaultDisplayDpi = changedConfig.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07004786 updateDefaultDensity();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004787 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 }
Bob Leee5408332009-09-04 18:31:17 -07004789
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004790 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004791 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004792 if (r == null) {
4793 return;
4794 }
Bob Leee5408332009-09-04 18:31:17 -07004795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 r.activity.mConfigChangeFlags |= configChanges;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004797 r.mPreserveWindow = tmp.mPreserveWindow;
Bob Leee5408332009-09-04 18:31:17 -07004798
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004799 r.activity.mChangingConfigurations = true;
4800
Robert Carr23fa16b2016-01-13 13:19:58 -08004801 // If we are preserving the main window across relaunches we would also like to preserve
4802 // the children. However the client side view system does not support preserving
4803 // the child views so we notify the window manager to expect these windows to
4804 // be replaced and defer requests to destroy or hide them. This way we can achieve
4805 // visual continuity. It's important that we do this here prior to pause and destroy
4806 // as that is when we may hide or remove the child views.
Robert Carr77bdfb52016-05-02 18:18:31 -07004807 //
4808 // There is another scenario, if we have decided locally to relaunch the app from a
4809 // call to recreate, then none of the windows will be prepared for replacement or
4810 // preserved by the server, so we want to notify it that we are preparing to replace
4811 // everything
Robert Carr23fa16b2016-01-13 13:19:58 -08004812 try {
Andrii Kulianb372da62018-01-18 10:46:24 -08004813 if (r.mPreserveWindow) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004814 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
Andrii Kulianb372da62018-01-18 10:46:24 -08004815 r.token, true /* childrenOnly */);
Robert Carr23fa16b2016-01-13 13:19:58 -08004816 }
4817 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004818 throw e.rethrowFromSystemServer();
Robert Carr23fa16b2016-01-13 13:19:58 -08004819 }
4820
Wale Ogunwale5527a502018-02-20 18:18:21 -08004821 handleRelaunchActivityInner(r, configChanges, tmp.pendingResults, tmp.pendingIntents,
4822 pendingActions, tmp.startsNotResumed, tmp.overrideConfig, "handleRelaunchActivity");
4823
4824 if (pendingActions != null) {
4825 // Only report a successful relaunch to WindowManager.
4826 pendingActions.setReportRelaunchToWindowManager(true);
Dianne Hackborne2b04802010-12-09 09:24:55 -08004827 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08004828 }
4829
Andrii Kulian320e3b52018-05-03 16:26:25 -07004830 /**
4831 * Post a message to relaunch the activity. We do this instead of launching it immediately,
4832 * because this will destroy the activity from which it was called and interfere with the
4833 * lifecycle changes it was going through before. We need to make sure that we have finished
4834 * handling current transaction item before relaunching the activity.
4835 */
4836 void scheduleRelaunchActivity(IBinder token) {
4837 sendMessage(H.RELAUNCH_ACTIVITY, token);
4838 }
Bob Leee5408332009-09-04 18:31:17 -07004839
Andrii Kulian320e3b52018-05-03 16:26:25 -07004840 /** Performs the activity relaunch locally vs. requesting from system-server. */
4841 private void handleRelaunchActivityLocally(IBinder token) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004842 final ActivityClientRecord r = mActivities.get(token);
4843 if (r == null) {
Andrii Kulian320e3b52018-05-03 16:26:25 -07004844 Log.w(TAG, "Activity to relaunch no longer exists");
Wale Ogunwale5527a502018-02-20 18:18:21 -08004845 return;
4846 }
4847
4848 final int prevState = r.getLifecycleState();
4849
Andrii Kulian320e3b52018-05-03 16:26:25 -07004850 if (prevState < ON_RESUME || prevState > ON_STOP) {
4851 Log.w(TAG, "Activity state must be in [ON_RESUME..ON_STOP] in order to be relaunched,"
4852 + "current state is " + prevState);
Wale Ogunwale5527a502018-02-20 18:18:21 -08004853 return;
4854 }
4855
Wale Ogunwale5527a502018-02-20 18:18:21 -08004856
Andrii Kulian914aa7d2018-03-19 21:51:53 -07004857 // Initialize a relaunch request.
4858 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
4859 r.createdConfig != null ? r.createdConfig : mConfiguration,
4860 r.overrideConfig);
4861 final ActivityRelaunchItem activityRelaunchItem = ActivityRelaunchItem.obtain(
4862 null /* pendingResults */, null /* pendingIntents */, 0 /* configChanges */,
4863 mergedConfiguration, r.mPreserveWindow);
4864 // Make sure to match the existing lifecycle state in the end of the transaction.
4865 final ActivityLifecycleItem lifecycleRequest =
4866 TransactionExecutorHelper.getLifecycleRequestForCurrentState(r);
4867 // Schedule the transaction.
4868 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
4869 transaction.addCallback(activityRelaunchItem);
4870 transaction.setLifecycleStateRequest(lifecycleRequest);
4871 executeTransaction(transaction);
Wale Ogunwale5527a502018-02-20 18:18:21 -08004872 }
4873
4874 private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
4875 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
4876 PendingTransactionActions pendingActions, boolean startsNotResumed,
4877 Configuration overrideConfig, String reason) {
Andrii Kulian770c4032018-05-02 18:40:59 -07004878 // Preserve last used intent, it may be set from Activity#setIntent().
4879 final Intent customIntent = r.activity.mIntent;
Wale Ogunwale5527a502018-02-20 18:18:21 -08004880 // Need to ensure state is saved.
4881 if (!r.paused) {
4882 performPauseActivity(r, false, reason, null /* pendingActions */);
4883 }
4884 if (!r.stopped) {
4885 callActivityOnStop(r, true /* saveState */, reason);
4886 }
4887
4888 handleDestroyActivity(r.token, false, configChanges, true, reason);
Bob Leee5408332009-09-04 18:31:17 -07004889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 r.activity = null;
4891 r.window = null;
4892 r.hideForNow = false;
4893 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07004894 // Merge any pending results and pending intents; don't just replace them
Wale Ogunwale5527a502018-02-20 18:18:21 -08004895 if (pendingResults != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07004896 if (r.pendingResults == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004897 r.pendingResults = pendingResults;
The Android Open Source Project10592532009-03-18 17:39:46 -07004898 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004899 r.pendingResults.addAll(pendingResults);
The Android Open Source Project10592532009-03-18 17:39:46 -07004900 }
4901 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08004902 if (pendingIntents != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07004903 if (r.pendingIntents == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004904 r.pendingIntents = pendingIntents;
The Android Open Source Project10592532009-03-18 17:39:46 -07004905 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004906 r.pendingIntents.addAll(pendingIntents);
The Android Open Source Project10592532009-03-18 17:39:46 -07004907 }
4908 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08004909 r.startsNotResumed = startsNotResumed;
4910 r.overrideConfig = overrideConfig;
Bob Leee5408332009-09-04 18:31:17 -07004911
Andrii Kulian770c4032018-05-02 18:40:59 -07004912 handleLaunchActivity(r, pendingActions, customIntent);
Andrii Kulianb372da62018-01-18 10:46:24 -08004913 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004914
Andrii Kulianb372da62018-01-18 10:46:24 -08004915 @Override
4916 public void reportRelaunch(IBinder token, PendingTransactionActions pendingActions) {
4917 try {
4918 ActivityManager.getService().activityRelaunched(token);
4919 final ActivityClientRecord r = mActivities.get(token);
4920 if (pendingActions.shouldReportRelaunchToWindowManager() && r != null
4921 && r.window != null) {
4922 r.window.reportActivityRelaunched();
Jorim Jaggife89d122015-12-22 16:28:44 +01004923 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004924 } catch (RemoteException e) {
4925 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01004926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004927 }
4928
Andrii Kulian8ae79572018-01-26 15:36:06 -08004929 private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
Craig Mautnera0026042014-04-23 11:45:37 -07004930 r.state = new Bundle();
4931 r.state.setAllowFds(false);
4932 if (r.isPersistable()) {
4933 r.persistentState = new PersistableBundle();
4934 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
4935 r.persistentState);
4936 } else {
4937 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
4938 }
4939 }
4940
Dianne Hackborn73c14162012-09-19 15:45:06 -07004941 ArrayList<ComponentCallbacks2> collectComponentCallbacks(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004943 ArrayList<ComponentCallbacks2> callbacks
4944 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07004945
Craig Mautner88c05892013-06-28 09:47:45 -07004946 synchronized (mResourcesManager) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004947 final int NAPP = mAllApplications.size();
4948 for (int i=0; i<NAPP; i++) {
Dianne Hackborn73c14162012-09-19 15:45:06 -07004949 callbacks.add(mAllApplications.get(i));
4950 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004951 final int NACT = mActivities.size();
4952 for (int i=0; i<NACT; i++) {
4953 ActivityClientRecord ar = mActivities.valueAt(i);
4954 Activity a = ar.activity;
4955 if (a != null) {
4956 Configuration thisConfig = applyConfigCompatMainThread(
4957 mCurDefaultDisplayDpi, newConfig,
Todd Kennedy233a0b12018-01-29 20:30:24 +00004958 ar.packageInfo.getCompatibilityInfo());
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004959 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
4960 // If the activity is currently resumed, its configuration
4961 // needs to change right now.
4962 callbacks.add(a);
4963 } else if (thisConfig != null) {
4964 // Otherwise, we will tell it about the change
4965 // the next time it is resumed or shown. Note that
4966 // the activity manager may, before then, decide the
4967 // activity needs to be destroyed to handle its new
4968 // configuration.
4969 if (DEBUG_CONFIGURATION) {
4970 Slog.v(TAG, "Setting activity "
4971 + ar.activityInfo.name + " newConfig=" + thisConfig);
Romain Guya998dff2012-03-23 18:58:36 -07004972 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004973 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004974 }
4975 }
4976 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004977 final int NSVC = mServices.size();
4978 for (int i=0; i<NSVC; i++) {
4979 callbacks.add(mServices.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 }
4981 }
4982 synchronized (mProviderMap) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004983 final int NPRV = mLocalProviders.size();
4984 for (int i=0; i<NPRV; i++) {
4985 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 }
4987 }
Bob Leee5408332009-09-04 18:31:17 -07004988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004989 return callbacks;
4990 }
Bob Leee5408332009-09-04 18:31:17 -07004991
Adam Lesinski082614c2016-03-04 14:33:47 -08004992 /**
4993 * Updates the configuration for an Activity. The ActivityClientRecord's
4994 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
4995 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
4996 * the updated Configuration.
4997 * @param r ActivityClientRecord representing the Activity.
4998 * @param newBaseConfig The new configuration to use. This may be augmented with
4999 * {@link ActivityClientRecord#overrideConfig}.
Adam Lesinski082614c2016-03-04 14:33:47 -08005000 */
5001 private void performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005002 Configuration newBaseConfig) {
5003 performConfigurationChangedForActivity(r, newBaseConfig,
5004 r.activity.getDisplay().getDisplayId(), false /* movedToDifferentDisplay */);
5005 }
5006
5007 /**
5008 * Updates the configuration for an Activity. The ActivityClientRecord's
5009 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5010 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5011 * the updated Configuration.
5012 * @param r ActivityClientRecord representing the Activity.
5013 * @param newBaseConfig The new configuration to use. This may be augmented with
5014 * {@link ActivityClientRecord#overrideConfig}.
5015 * @param displayId The id of the display where the Activity currently resides.
5016 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005017 * @return {@link Configuration} instance sent to client, null if not sent.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005018 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005019 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005020 Configuration newBaseConfig, int displayId, boolean movedToDifferentDisplay) {
Adam Lesinski082614c2016-03-04 14:33:47 -08005021 r.tmpConfig.setTo(newBaseConfig);
5022 if (r.overrideConfig != null) {
5023 r.tmpConfig.updateFrom(r.overrideConfig);
5024 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005025 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
5026 r.tmpConfig, r.overrideConfig, displayId, movedToDifferentDisplay);
Adam Lesinski082614c2016-03-04 14:33:47 -08005027 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005028 return reportedConfig;
Adam Lesinski082614c2016-03-04 14:33:47 -08005029 }
5030
5031 /**
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005032 * Creates a new Configuration only if override would modify base. Otherwise returns base.
5033 * @param base The base configuration.
5034 * @param override The update to apply to the base configuration. Can be null.
5035 * @return A Configuration representing base with override applied.
5036 */
5037 private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
5038 @Nullable Configuration override) {
5039 if (override == null) {
5040 return base;
5041 }
5042 Configuration newConfig = new Configuration(base);
5043 newConfig.updateFrom(override);
5044 return newConfig;
5045 }
5046
5047 /**
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005048 * Decides whether to update a component's configuration and whether to inform it.
Adam Lesinski082614c2016-03-04 14:33:47 -08005049 * @param cb The component callback to notify of configuration change.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005050 * @param newConfig The new configuration.
5051 */
5052 private void performConfigurationChanged(ComponentCallbacks2 cb, Configuration newConfig) {
5053 if (!REPORT_TO_ACTIVITY) {
5054 return;
5055 }
5056
5057 // ContextThemeWrappers may override the configuration for that context. We must check and
5058 // apply any overrides defined.
5059 Configuration contextThemeWrapperOverrideConfig = null;
5060 if (cb instanceof ContextThemeWrapper) {
5061 final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
5062 contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
5063 }
5064
5065 // Apply the ContextThemeWrapper override if necessary.
5066 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5067 // in many places.
5068 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
5069 newConfig, contextThemeWrapperOverrideConfig);
5070 cb.onConfigurationChanged(configToReport);
5071 }
5072
5073 /**
5074 * Decides whether to update an Activity's configuration and whether to inform it.
5075 * @param activity The activity to notify of configuration change.
Adam Lesinski082614c2016-03-04 14:33:47 -08005076 * @param newConfig The new configuration.
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005077 * @param amOverrideConfig The override config that differentiates the Activity's configuration
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005078 * from the base global configuration. This is supplied by
5079 * ActivityManager.
5080 * @param displayId Id of the display where activity currently resides.
5081 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005082 * @return Configuration sent to client, null if no changes and not moved to different display.
Adam Lesinski082614c2016-03-04 14:33:47 -08005083 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005084 private Configuration performActivityConfigurationChanged(Activity activity,
5085 Configuration newConfig, Configuration amOverrideConfig, int displayId,
5086 boolean movedToDifferentDisplay) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005087 if (activity == null) {
5088 throw new IllegalArgumentException("No activity provided.");
5089 }
5090 final IBinder activityToken = activity.getActivityToken();
5091 if (activityToken == null) {
5092 throw new IllegalArgumentException("Activity token not set. Is the activity attached?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 }
Bob Leee5408332009-09-04 18:31:17 -07005094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005095 boolean shouldChangeConfig = false;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005096 if (activity.mCurrentConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 shouldChangeConfig = true;
5098 } else {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005099 // If the new config is the same as the config this Activity is already running with and
5100 // the override config also didn't change, then don't bother calling
5101 // onConfigurationChanged.
Bryce Lee658d9842017-07-28 08:33:36 -07005102 final int diff = activity.mCurrentConfig.diffPublicOnly(newConfig);
5103
Andrii Kulian3b3c9142016-07-18 19:15:56 -07005104 if (diff != 0 || !mResourcesManager.isSameResourcesOverrideConfig(activityToken,
5105 amOverrideConfig)) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005106 // Always send the task-level config changes. For system-level configuration, if
5107 // this activity doesn't handle any of the config changes, then don't bother
5108 // calling onConfigurationChanged as we're going to destroy it.
5109 if (!mUpdatingSystemConfig
5110 || (~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005111 || !REPORT_TO_ACTIVITY) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005112 shouldChangeConfig = true;
5113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 }
5115 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005116 if (!shouldChangeConfig && !movedToDifferentDisplay) {
5117 // Nothing significant, don't proceed with updating and reporting.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005118 return null;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005119 }
5120
5121 // Propagate the configuration change to ResourcesManager and Activity.
5122
5123 // ContextThemeWrappers may override the configuration for that context. We must check and
5124 // apply any overrides defined.
5125 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
5126
5127 // We only update an Activity's configuration if this is not a global configuration change.
5128 // This must also be done before the callback, or else we violate the contract that the new
5129 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
5130 // Also apply the ContextThemeWrapper override if necessary.
5131 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
5132 // many places.
5133 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
5134 amOverrideConfig, contextThemeWrapperOverrideConfig);
5135 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig,
5136 displayId, movedToDifferentDisplay);
5137
5138 activity.mConfigChangeFlags = 0;
5139 activity.mCurrentConfig = new Configuration(newConfig);
5140
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005141 // Apply the ContextThemeWrapper override if necessary.
5142 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5143 // in many places.
5144 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
5145 contextThemeWrapperOverrideConfig);
5146
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005147 if (!REPORT_TO_ACTIVITY) {
5148 // Not configured to report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005149 return configToReport;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005150 }
5151
5152 if (movedToDifferentDisplay) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005153 activity.dispatchMovedToDisplay(displayId, configToReport);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005154 }
Bob Leee5408332009-09-04 18:31:17 -07005155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 if (shouldChangeConfig) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005157 activity.mCalled = false;
5158 activity.onConfigurationChanged(configToReport);
5159 if (!activity.mCalled) {
5160 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
5161 " did not call through to super.onConfigurationChanged()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 }
5163 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005164
5165 return configToReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 }
5167
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005168 public final void applyConfigurationToResources(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -07005169 synchronized (mResourcesManager) {
5170 mResourcesManager.applyConfigurationToResourcesLocked(config, null);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005171 }
5172 }
5173
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005174 final Configuration applyCompatConfiguration(int displayDensity) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005175 Configuration config = mConfiguration;
5176 if (mCompatConfiguration == null) {
5177 mCompatConfiguration = new Configuration();
5178 }
5179 mCompatConfiguration.setTo(mConfiguration);
Adam Lesinski082614c2016-03-04 14:33:47 -08005180 if (mResourcesManager.applyCompatConfigurationLocked(displayDensity,
5181 mCompatConfiguration)) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005182 config = mCompatConfiguration;
5183 }
5184 return config;
5185 }
5186
Andrii Kulian446e8242017-10-26 15:17:29 -07005187 @Override
5188 public void handleConfigurationChanged(Configuration config) {
5189 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
5190 mCurDefaultDisplayDpi = config.densityDpi;
5191 mUpdatingSystemConfig = true;
5192 try {
5193 handleConfigurationChanged(config, null /* compat */);
5194 } finally {
5195 mUpdatingSystemConfig = false;
5196 }
5197 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5198 }
5199
5200 private void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005201
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005202 int configDiff = 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005203
Bryce Lee658d9842017-07-28 08:33:36 -07005204 // This flag tracks whether the new configuration is fundamentally equivalent to the
5205 // existing configuration. This is necessary to determine whether non-activity
5206 // callbacks should receive notice when the only changes are related to non-public fields.
5207 // We do not gate calling {@link #performActivityConfigurationChanged} based on this flag
5208 // as that method uses the same check on the activity config override as well.
5209 final boolean equivalent = config != null && mConfiguration != null
5210 && (0 == mConfiguration.diffPublicOnly(config));
Todd Kennedy35a9a382018-01-25 13:25:37 -08005211 final Theme systemTheme = getSystemContext().getTheme();
5212 final Theme systemUiTheme = getSystemUiContext().getTheme();
Bryce Lee658d9842017-07-28 08:33:36 -07005213
Craig Mautner88c05892013-06-28 09:47:45 -07005214 synchronized (mResourcesManager) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005215 if (mPendingConfiguration != null) {
5216 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
5217 config = mPendingConfiguration;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005218 mCurDefaultDisplayDpi = config.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005219 updateDefaultDensity();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005220 }
5221 mPendingConfiguration = null;
5222 }
5223
5224 if (config == null) {
5225 return;
5226 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005227
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005228 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005229 + config);
Craig Mautner88c05892013-06-28 09:47:45 -07005230
5231 mResourcesManager.applyConfigurationToResourcesLocked(config, compat);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005232 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
5233 mResourcesManager.getConfiguration().getLocales());
Craig Mautner88c05892013-06-28 09:47:45 -07005234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 if (mConfiguration == null) {
5236 mConfiguration = new Configuration();
5237 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005238 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005239 return;
5240 }
Alan Viverettee54d2452015-05-06 10:41:43 -07005241
5242 configDiff = mConfiguration.updateFrom(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005243 config = applyCompatConfiguration(mCurDefaultDisplayDpi);
Alan Viverette395cd012015-08-11 17:27:04 -04005244
Alan Viverette395cd012015-08-11 17:27:04 -04005245 if ((systemTheme.getChangingConfigurations() & configDiff) != 0) {
5246 systemTheme.rebase();
5247 }
Adam Lesinskia82b6262017-03-21 16:56:17 -07005248
Adam Lesinskia82b6262017-03-21 16:56:17 -07005249 if ((systemUiTheme.getChangingConfigurations() & configDiff) != 0) {
5250 systemUiTheme.rebase();
5251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005252 }
Dianne Hackborn73c14162012-09-19 15:45:06 -07005253
5254 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(false, config);
5255
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005256 freeTextLayoutCachesIfNeeded(configDiff);
5257
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005258 if (callbacks != null) {
5259 final int N = callbacks.size();
5260 for (int i=0; i<N; i++) {
Andrii Kulian701214b2016-04-07 09:36:33 -07005261 ComponentCallbacks2 cb = callbacks.get(i);
5262 if (cb instanceof Activity) {
5263 // If callback is an Activity - call corresponding method to consider override
5264 // config and avoid onConfigurationChanged if it hasn't changed.
5265 Activity a = (Activity) cb;
5266 performConfigurationChangedForActivity(mActivities.get(a.getActivityToken()),
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005267 config);
Bryce Lee658d9842017-07-28 08:33:36 -07005268 } else if (!equivalent) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005269 performConfigurationChanged(cb, config);
Andrii Kulian701214b2016-04-07 09:36:33 -07005270 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272 }
5273 }
5274
Adrian Roos9ee5dff2018-08-22 20:19:49 +02005275 /**
5276 * Updates the application info.
5277 *
5278 * This only works in the system process. Must be called on the main thread.
5279 */
5280 public void handleSystemApplicationInfoChanged(@NonNull ApplicationInfo ai) {
5281 Preconditions.checkState(mSystemThread, "Must only be called in the system process");
5282 handleApplicationInfoChanged(ai);
5283 }
5284
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005285 void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
Adam Lesinskid33ef562017-01-19 14:49:59 -08005286 // Updates triggered by package installation go through a package update
5287 // receiver. Here we try to capture ApplicationInfo changes that are
5288 // caused by other sources, such as overlays. That means we want to be as conservative
5289 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
5290 // to see if anything needs to change.
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005291 LoadedApk apk;
5292 LoadedApk resApk;
5293 // Update all affected loaded packages with new package information
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005294 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005295 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005296 apk = ref != null ? ref.get() : null;
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005297 ref = mResourcePackages.get(ai.packageName);
5298 resApk = ref != null ? ref.get() : null;
5299 }
5300 if (apk != null) {
5301 final ArrayList<String> oldPaths = new ArrayList<>();
5302 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
5303 apk.updateApplicationInfo(ai, oldPaths);
5304 }
5305 if (resApk != null) {
5306 final ArrayList<String> oldPaths = new ArrayList<>();
5307 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
5308 resApk.updateApplicationInfo(ai, oldPaths);
5309 }
5310 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005311 // Update all affected Resources objects to use new ResourcesImpl
5312 mResourcesManager.applyNewResourceDirsLocked(ai.sourceDir, ai.resourceDirs);
5313 }
5314
5315 ApplicationPackageManager.configurationChanged();
5316
5317 // Trigger a regular Configuration change event, only with a different assetsSeq number
5318 // so that we actually call through to all components.
Adam Lesinskia82b6262017-03-21 16:56:17 -07005319 // TODO(adamlesinski): Change this to make use of ActivityManager's upcoming ability to
5320 // store configurations per-process.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005321 Configuration newConfig = new Configuration();
Adam Lesinskia82b6262017-03-21 16:56:17 -07005322 newConfig.assetsSeq = (mConfiguration != null ? mConfiguration.assetsSeq : 0) + 1;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005323 handleConfigurationChanged(newConfig, null);
5324
Wale Ogunwale5527a502018-02-20 18:18:21 -08005325 relaunchAllActivities();
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005326 }
5327
Romain Guy46bfc482013-08-16 18:38:29 -07005328 static void freeTextLayoutCachesIfNeeded(int configDiff) {
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005329 if (configDiff != 0) {
5330 // Ask text layout engine to free its caches if there is a locale change
5331 boolean hasLocaleConfigChange = ((configDiff & ActivityInfo.CONFIG_LOCALE) != 0);
5332 if (hasLocaleConfigChange) {
5333 Canvas.freeTextLayoutCaches();
5334 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Cleared TextLayout Caches");
5335 }
5336 }
5337 }
5338
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005339 /**
5340 * Handle new activity configuration and/or move to a different display.
Andrii Kulian446e8242017-10-26 15:17:29 -07005341 * @param activityToken Target activity token.
5342 * @param overrideConfig Activity override config.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005343 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
5344 * value didn't change.
5345 */
Andrii Kulian446e8242017-10-26 15:17:29 -07005346 @Override
5347 public void handleActivityConfigurationChanged(IBinder activityToken,
5348 Configuration overrideConfig, int displayId) {
5349 ActivityClientRecord r = mActivities.get(activityToken);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005350 // Check input params.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005351 if (r == null || r.activity == null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005352 if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005353 return;
5354 }
Andrii Kulian51c1b672017-04-07 18:39:32 -07005355 final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
5356 && displayId != r.activity.getDisplay().getDisplayId();
Bob Leee5408332009-09-04 18:31:17 -07005357
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005358 // Perform updates.
Andrii Kulian446e8242017-10-26 15:17:29 -07005359 r.overrideConfig = overrideConfig;
Stephen Kiazykf903b732017-03-20 16:23:45 -07005360 final ViewRootImpl viewRoot = r.activity.mDecor != null
5361 ? r.activity.mDecor.getViewRootImpl() : null;
5362
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005363 if (movedToDifferentDisplay) {
5364 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity moved to display, activity:"
5365 + r.activityInfo.name + ", displayId=" + displayId
Andrii Kulian446e8242017-10-26 15:17:29 -07005366 + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005367
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005368 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
5369 mCompatConfiguration, displayId, true /* movedToDifferentDisplay */);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005370 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005371 viewRoot.onMovedToDisplay(displayId, reportedConfig);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005372 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005373 } else {
5374 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Andrii Kulian446e8242017-10-26 15:17:29 -07005375 + r.activityInfo.name + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005376 performConfigurationChangedForActivity(r, mCompatConfiguration);
5377 }
Andrii Kulian44607962017-03-16 11:06:24 -07005378 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
5379 // update to make sure that resources are updated before updating itself.
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005380 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005381 viewRoot.updateConfiguration(displayId);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005382 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005383 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 }
5385
Jeff Hao1b012d32014-08-20 10:35:34 -07005386 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005387 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005388 try {
Romain Guy7eabe552011-07-21 14:56:34 -07005389 switch (profileType) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005390 default:
5391 mProfiler.setProfiler(profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005392 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005393 break;
5394 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005395 } catch (RuntimeException e) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005396 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005397 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07005398 } finally {
Andreas Gampe2b073a02017-06-22 17:28:57 -07005399 profilerInfo.closeFd();
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005400 }
5401 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07005402 switch (profileType) {
Romain Guy7eabe552011-07-21 14:56:34 -07005403 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005404 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005405 break;
Romain Guy7eabe552011-07-21 14:56:34 -07005406 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005407 }
5408 }
Bob Leee5408332009-09-04 18:31:17 -07005409
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005410 /**
5411 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
5412 * so that profiler data won't be lost.
5413 *
5414 * @hide
5415 */
5416 public void stopProfiling() {
Amith Yamasanib1684432017-01-26 14:57:20 -08005417 if (mProfiler != null) {
5418 mProfiler.stopProfiling();
5419 }
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005420 }
5421
Christopher Ferris8d652f82017-04-11 16:29:18 -07005422 static void handleDumpHeap(DumpHeapData dhd) {
Makoto Onuki4556b7b2017-07-07 14:58:58 -07005423 if (dhd.runGc) {
5424 System.gc();
5425 System.runFinalization();
5426 System.gc();
5427 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005428 if (dhd.managed) {
Andy McFadden824c5102010-07-09 16:26:57 -07005429 try {
5430 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
5431 } catch (IOException e) {
5432 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
5433 + " -- can the process access this path?");
5434 } finally {
5435 try {
5436 dhd.fd.close();
5437 } catch (IOException e) {
5438 Slog.w(TAG, "Failure closing profile fd", e);
5439 }
5440 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005441 } else if (dhd.mallocInfo) {
5442 Debug.dumpNativeMallocInfo(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005443 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07005444 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005445 }
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005446 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005447 ActivityManager.getService().dumpHeapFinished(dhd.path);
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005448 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005449 throw e.rethrowFromSystemServer();
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005450 }
Andy McFadden824c5102010-07-09 16:26:57 -07005451 }
5452
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005453 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005454 boolean hasPkgInfo = false;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005455 switch (cmd) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005456 case ApplicationThreadConstants.PACKAGE_REMOVED:
5457 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005458 {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005459 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005460 if (packages == null) {
5461 break;
5462 }
5463 synchronized (mResourcesManager) {
5464 for (int i = packages.length - 1; i >= 0; i--) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005465 if (!hasPkgInfo) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005466 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
5467 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005468 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005469 } else {
5470 ref = mResourcePackages.get(packages[i]);
5471 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005472 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005473 }
5474 }
5475 }
5476 if (killApp) {
5477 mPackages.remove(packages[i]);
5478 mResourcePackages.remove(packages[i]);
5479 }
5480 }
5481 }
5482 break;
5483 }
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005484 case ApplicationThreadConstants.PACKAGE_REPLACED:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005485 {
5486 if (packages == null) {
5487 break;
5488 }
5489 synchronized (mResourcesManager) {
5490 for (int i = packages.length - 1; i >= 0; i--) {
5491 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005492 LoadedApk pkgInfo = ref != null ? ref.get() : null;
5493 if (pkgInfo != null) {
5494 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005495 } else {
5496 ref = mResourcePackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005497 pkgInfo = ref != null ? ref.get() : null;
5498 if (pkgInfo != null) {
5499 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005500 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005501 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005502 // If the package is being replaced, yet it still has a valid
5503 // LoadedApk object, the package was updated with _DONT_KILL.
5504 // Adjust it's internal references to the application info and
5505 // resources.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005506 if (pkgInfo != null) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005507 try {
5508 final String packageName = packages[i];
5509 final ApplicationInfo aInfo =
5510 sPackageManager.getApplicationInfo(
5511 packageName,
Svet Ganov6ce92392017-09-27 16:04:10 -07005512 PackageManager.GET_SHARED_LIBRARY_FILES,
Todd Kennedy39bfee52016-02-24 10:28:21 -08005513 UserHandle.myUserId());
5514
5515 if (mActivities.size() > 0) {
5516 for (ActivityClientRecord ar : mActivities.values()) {
5517 if (ar.activityInfo.applicationInfo.packageName
5518 .equals(packageName)) {
5519 ar.activityInfo.applicationInfo = aInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00005520 ar.packageInfo = pkgInfo;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005521 }
5522 }
5523 }
Todd Kennedyb9656a92018-05-02 10:59:45 +01005524 final ArrayList<String> oldPaths = new ArrayList<>();
5525 LoadedApk.makePaths(this, pkgInfo.getApplicationInfo(), oldPaths);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005526 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
Todd Kennedy39bfee52016-02-24 10:28:21 -08005527 } catch (RemoteException e) {
5528 }
5529 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005530 }
5531 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005532 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005533 }
5534 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00005535 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005536 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 final void handleLowMemory() {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005539 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Bob Leee5408332009-09-04 18:31:17 -07005540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 final int N = callbacks.size();
5542 for (int i=0; i<N; i++) {
5543 callbacks.get(i).onLowMemory();
5544 }
5545
Chris Tatece229052009-03-25 16:44:52 -07005546 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
5547 if (Process.myUid() != Process.SYSTEM_UID) {
5548 int sqliteReleased = SQLiteDatabase.releaseMemory();
5549 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
5550 }
Bob Leee5408332009-09-04 18:31:17 -07005551
Mike Reedcaf0df12009-04-27 14:32:05 -04005552 // Ask graphics to free up as much as possible (font/image caches)
5553 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005555 // Ask text layout engine to free also as much as possible
5556 Canvas.freeTextLayoutCaches();
5557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 BinderInternal.forceGc("mem");
5559 }
5560
Jorim Jaggib29e3182018-04-30 18:51:56 +02005561 private void handleTrimMemory(int level) {
5562 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07005563 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005564
Dianne Hackborn73c14162012-09-19 15:45:06 -07005565 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005566
5567 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07005568 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005569 callbacks.get(i).onTrimMemory(level);
5570 }
Romain Guy19f86e82012-04-23 15:19:07 -07005571
John Reckf47a5942014-06-30 16:20:04 -07005572 WindowManagerGlobal.getInstance().trimMemory(level);
Jorim Jaggib29e3182018-04-30 18:51:56 +02005573 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005574 }
5575
Jesse Hall317fa5a2017-05-23 15:46:55 -07005576 private void setupGraphicsSupport(Context context) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005577 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
Romain Guya9582652011-11-10 14:20:10 -08005578
Jesse Hall317fa5a2017-05-23 15:46:55 -07005579 // The system package doesn't have real data directories, so don't set up cache paths.
5580 if (!"android".equals(context.getPackageName())) {
5581 // This cache location probably points at credential-encrypted
5582 // storage which may not be accessible yet; assign it anyway instead
5583 // of pointing at device-encrypted storage.
5584 final File cacheDir = context.getCacheDir();
5585 if (cacheDir != null) {
5586 // Provide a usable directory for temporary files
5587 System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
5588 } else {
5589 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
5590 + "due to missing cache directory");
Romain Guya9582652011-11-10 14:20:10 -08005591 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005592
5593 // Setup a location to store generated/compiled graphics code.
5594 final Context deviceContext = context.createDeviceProtectedStorageContext();
5595 final File codeCacheDir = deviceContext.getCodeCacheDir();
5596 if (codeCacheDir != null) {
5597 try {
5598 int uid = Process.myUid();
5599 String[] packages = getPackageManager().getPackagesForUid(uid);
5600 if (packages != null) {
Romain Guycecbe072017-07-18 15:42:06 -07005601 ThreadedRenderer.setupDiskCache(codeCacheDir);
5602 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005603 }
5604 } catch (RemoteException e) {
5605 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5606 throw e.rethrowFromSystemServer();
5607 }
5608 } else {
5609 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
5610 }
Romain Guya9582652011-11-10 14:20:10 -08005611 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005612
Cody Northrop86cedcb2017-10-20 09:03:13 -06005613 GraphicsEnvironment.getInstance().setup(context);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005614 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005615 }
5616
5617 private void updateDefaultDensity() {
Alan Viverette2ac46f12016-02-04 16:58:14 -05005618 final int densityDpi = mCurDefaultDisplayDpi;
5619 if (!mDensityCompatMode
5620 && densityDpi != Configuration.DENSITY_DPI_UNDEFINED
5621 && densityDpi != DisplayMetrics.DENSITY_DEVICE) {
5622 DisplayMetrics.DENSITY_DEVICE = densityDpi;
5623 Bitmap.setDefaultDensity(densityDpi);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005624 }
5625 }
5626
Todd Kennedye713efc2016-05-10 13:45:40 -07005627 /**
5628 * Returns the correct library directory for the current ABI.
5629 * <p>
5630 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
5631 * libraries, we might need to choose the secondary depending on what the current
5632 * runtime's instruction set is.
5633 */
5634 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
Patrick Baumanneb595802018-04-17 09:49:55 -07005635 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null
5636 && appInfo.secondaryCpuAbi.equals(insInfo.secondaryCpuAbi)) {
Todd Kennedye713efc2016-05-10 13:45:40 -07005637 // Get the instruction set supported by the secondary ABI. In the presence
5638 // of a native bridge this might be different than the one secondary ABI used.
5639 String secondaryIsa =
5640 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
5641 final String secondaryDexCodeIsa =
5642 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
5643 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
5644
5645 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
5646 if (runtimeIsa.equals(secondaryIsa)) {
5647 return insInfo.secondaryNativeLibraryDir;
5648 }
5649 }
5650 return insInfo.nativeLibraryDir;
5651 }
5652
Adam Lesinskib61e4052016-05-19 18:23:05 -07005653 /**
5654 * The LocaleList set for the app's resources may have been shuffled so that the preferred
5655 * Locale is at position 0. We must find the index of this preferred Locale in the
5656 * original LocaleList.
5657 */
5658 private void updateLocaleListFromAppContext(Context context, LocaleList newLocaleList) {
5659 final Locale bestLocale = context.getResources().getConfiguration().getLocales().get(0);
5660 final int newLocaleListSize = newLocaleList.size();
5661 for (int i = 0; i < newLocaleListSize; i++) {
5662 if (bestLocale.equals(newLocaleList.get(i))) {
5663 LocaleList.setDefault(newLocaleList, i);
5664 return;
5665 }
5666 }
Adam Lesinski27d30162016-05-25 16:45:14 -07005667
5668 // The app may have overridden the LocaleList with its own Locale
5669 // (not present in the available list). Push the chosen Locale
5670 // to the front of the list.
5671 LocaleList.setDefault(new LocaleList(bestLocale, newLocaleList));
Adam Lesinskib61e4052016-05-19 18:23:05 -07005672 }
5673
Mathew Inwood4fb17d12018-08-14 14:25:44 +01005674 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07005675 private void handleBindApplication(AppBindData data) {
Calin Juravle8f5770d2016-04-12 14:12:04 +01005676 // Register the UI Thread as a sensitive thread to the runtime.
5677 VMRuntime.registerSensitiveThread();
Man Caocfa78b22015-06-11 20:14:34 -07005678 if (data.trackAllocation) {
5679 DdmVmInternal.enableRecentAllocations(true);
5680 }
5681
Dianne Hackbornd98885c2016-03-01 17:13:03 -08005682 // Note when this process has started.
5683 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
5684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 mBoundApplication = data;
5686 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07005687 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005689 mProfiler = new Profiler();
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005690 String agent = null;
Jeff Hao1b012d32014-08-20 10:35:34 -07005691 if (data.initProfilerInfo != null) {
5692 mProfiler.profileFile = data.initProfilerInfo.profileFile;
5693 mProfiler.profileFd = data.initProfilerInfo.profileFd;
5694 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
5695 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -08005696 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005697 if (data.initProfilerInfo.attachAgentDuringBind) {
5698 agent = data.initProfilerInfo.agent;
5699 }
Jeff Hao1b012d32014-08-20 10:35:34 -07005700 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08005703 Process.setArgV0(data.processName);
Siva Velusamyd693dfa2012-09-10 14:36:58 -07005704 android.ddm.DdmHandleAppName.setAppName(data.processName,
5705 UserHandle.myUserId());
Mathew Inwood37b6ca82018-05-02 10:42:23 +01005706 VMRuntime.setProcessPackageName(data.appInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005708 if (mProfiler.profileFd != null) {
5709 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07005710 }
5711
Joe Onoratod630f102011-03-17 18:42:26 -07005712 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
5713 // implementation to use the pool executor. Normally, we use the
5714 // serialized executor as the default. This has to happen in the
5715 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07005716 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07005717 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
5718 }
5719
Dianne Hackborn7895bc22014-09-05 15:09:03 -07005720 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
5721
Leon Scroggins III8290eab2018-03-19 10:51:44 -04005722 // Prior to P, internal calls to decode Bitmaps used BitmapFactory,
5723 // which may scale up to account for density. In P, we switched to
5724 // ImageDecoder, which skips the upscale to save memory. ImageDecoder
5725 // needs to still scale up in older apps, in case they rely on the
5726 // size of the Bitmap without considering its density.
5727 ImageDecoder.sApiLevel = data.appInfo.targetSdkVersion;
5728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 /*
5730 * Before spawning a new process, reset the time zone to be the system time zone.
5731 * This needs to be done because the system time zone could have changed after the
5732 * the spawning of this process. Without doing this this process would have the incorrect
5733 * system time zone.
5734 */
5735 TimeZone.setDefault(null);
5736
Adam Lesinskib61e4052016-05-19 18:23:05 -07005737 /*
5738 * Set the LocaleList. This may change once we create the App Context.
5739 */
5740 LocaleList.setDefault(data.config.getLocales());
5741
5742 synchronized (mResourcesManager) {
5743 /*
5744 * Update the system configuration since its preloaded and might not
5745 * reflect configuration changes. The configuration object passed
5746 * in AppBindData can be safely assumed to be up to date
5747 */
5748 mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
5749 mCurDefaultDisplayDpi = data.config.densityDpi;
5750
5751 // This calls mResourcesManager so keep it within the synchronized block.
5752 applyCompatConfiguration(mCurDefaultDisplayDpi);
5753 }
5754
Todd Kennedy233a0b12018-01-29 20:30:24 +00005755 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005757 if (agent != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005758 handleAttachAgent(agent, data.info);
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005759 }
5760
Dianne Hackborndde331c2012-08-03 14:01:57 -07005761 /**
5762 * Switch this process to density compatibility mode if needed.
5763 */
5764 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
5765 == 0) {
5766 mDensityCompatMode = true;
5767 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
5768 }
5769 updateDefaultDensity();
5770
Neil Fullerc66ec402016-11-14 16:06:42 +00005771 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
5772 Boolean is24Hr = null;
5773 if (use24HourSetting != null) {
5774 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
5775 }
5776 // null : use locale default for 12/24 hour formatting,
5777 // false : use 12 hour format,
5778 // true : use 24 hour format.
Narayan Kamathccb2a0862013-12-19 14:49:36 +00005779 DateFormat.set24HourTimePref(is24Hr);
5780
Jon Miranda836c0a82014-08-11 12:32:26 -07005781 View.mDebugViewAttributes =
5782 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
5783
Jeff Sharkey89182982017-11-01 19:02:56 -06005784 StrictMode.initThreadDefaults(data.appInfo);
5785 StrictMode.initVmDefaults(data.appInfo);
Jeff Sharkey344744b2016-01-28 19:03:30 -07005786
Svet Ganov37e43272016-09-09 16:01:32 -07005787 // We deprecated Build.SERIAL and only apps that target pre NMR1
5788 // SDK can see it. Since access to the serial is now behind a
5789 // permission we push down the value and here we fix it up
5790 // before any app code has been loaded.
5791 try {
5792 Field field = Build.class.getDeclaredField("SERIAL");
5793 field.setAccessible(true);
5794 field.set(Build.class, data.buildSerial);
5795 } catch (NoSuchFieldException | IllegalAccessException e) {
5796 /* ignore */
5797 }
5798
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005799 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 // XXX should have option to change the port.
5801 Debug.changeDebugPort(8100);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005802 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005803 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 + " is waiting for the debugger on port 8100...");
5805
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005806 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 try {
5808 mgr.showWaitingForDebugger(mAppThread, true);
5809 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005810 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 }
5812
5813 Debug.waitForDebugger();
5814
5815 try {
5816 mgr.showWaitingForDebugger(mAppThread, false);
5817 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005818 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 }
5820
5821 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005822 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 + " can be debugged on port 8100...");
5824 }
5825 }
5826
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005827 // Allow application-generated systrace messages if we're debuggable.
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04005828 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
5829 Trace.setAppTracingAllowed(isAppDebuggable);
John Reck56428472018-03-16 17:27:17 -07005830 ThreadedRenderer.setDebuggingEnabled(isAppDebuggable || Build.IS_DEBUGGABLE);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04005831 if (isAppDebuggable && data.enableBinderTracking) {
5832 Binder.enableTracing();
5833 }
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005834
Robert Greenwalt434203a2010-10-11 16:00:27 -07005835 /**
5836 * Initialize the default http proxy in this process for the reasons we set the time zone.
5837 */
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005838 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
Alan Viverettebe64eae2015-09-03 14:56:04 -04005839 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005840 if (b != null) {
5841 // In pre-boot mode (doing initial launch to collect password), not
5842 // all system is up. This includes the connectivity service, so don't
5843 // crash if we can't get it.
Alan Viverettebe64eae2015-09-03 14:56:04 -04005844 final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005845 try {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00005846 Proxy.setHttpProxySystemProperty(service.getProxyForNetwork(null));
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005847 } catch (RemoteException e) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005848 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005849 throw e.rethrowFromSystemServer();
5850 }
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005851 }
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005852 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Robert Greenwalt434203a2010-10-11 16:00:27 -07005853
Alan Viverette2107d692015-09-03 14:55:27 -04005854 // Instrumentation info affects the class loader, so load it before
5855 // setting up the app context.
5856 final InstrumentationInfo ii;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 if (data.instrumentationName != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 try {
Alan Viverette2107d692015-09-03 14:55:27 -04005859 ii = new ApplicationPackageManager(null, getPackageManager())
5860 .getInstrumentationInfo(data.instrumentationName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 } catch (PackageManager.NameNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 throw new RuntimeException(
Alan Viverette2107d692015-09-03 14:55:27 -04005863 "Unable to find instrumentation info for: " + data.instrumentationName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 }
5865
Patrick Baumanneb595802018-04-17 09:49:55 -07005866 // Warn of potential ABI mismatches.
5867 if (!Objects.equals(data.appInfo.primaryCpuAbi, ii.primaryCpuAbi)
5868 || !Objects.equals(data.appInfo.secondaryCpuAbi, ii.secondaryCpuAbi)) {
5869 Slog.w(TAG, "Package uses different ABI(s) than its instrumentation: "
5870 + "package[" + data.appInfo.packageName + "]: "
5871 + data.appInfo.primaryCpuAbi + ", " + data.appInfo.secondaryCpuAbi
5872 + " instrumentation[" + ii.packageName + "]: "
5873 + ii.primaryCpuAbi + ", " + ii.secondaryCpuAbi);
5874 }
5875
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005876 mInstrumentationPackageName = ii.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 mInstrumentationAppDir = ii.sourceDir;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005878 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
Todd Kennedye713efc2016-05-10 13:45:40 -07005879 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005880 mInstrumentedAppDir = data.info.getAppDir();
5881 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
5882 mInstrumentedLibDir = data.info.getLibDir();
Alan Viverette2107d692015-09-03 14:55:27 -04005883 } else {
5884 ii = null;
5885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005886
Todd Kennedy233a0b12018-01-29 20:30:24 +00005887 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005888 updateLocaleListFromAppContext(appContext,
5889 mResourcesManager.getConfiguration().getLocales());
Seigo Nonakac14dd782016-03-30 23:09:16 +09005890
Jesse Hall317fa5a2017-05-23 15:46:55 -07005891 if (!Process.isIsolated()) {
Jeff Sharkey89182982017-11-01 19:02:56 -06005892 final int oldMask = StrictMode.allowThreadDiskWritesMask();
5893 try {
5894 setupGraphicsSupport(appContext);
5895 } finally {
5896 StrictMode.setThreadPolicyMask(oldMask);
5897 }
John Reck56428472018-03-16 17:27:17 -07005898 } else {
5899 ThreadedRenderer.setIsolatedProcess(true);
Michael Lentine2ba303f2016-02-01 20:44:34 -06005900 }
Michael Lentine03d8f7682016-01-31 15:37:11 -06005901
Chad Brubaker78d47122015-11-17 22:26:58 -08005902 // Install the Network Security Config Provider. This must happen before the application
5903 // code is loaded to prevent issues with instances of TLS objects being created before
5904 // the provider is installed.
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005905 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
Chad Brubaker276ee962016-06-08 12:57:46 -07005906 NetworkSecurityConfigProvider.install(appContext);
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005907 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Chad Brubaker78d47122015-11-17 22:26:58 -08005908
Alan Viverette2107d692015-09-03 14:55:27 -04005909 // Continue loading instrumentation.
5910 if (ii != null) {
Dianne Hackbornf4ef6eb2017-12-07 13:57:21 -08005911 ApplicationInfo instrApp;
5912 try {
5913 instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
5914 UserHandle.myUserId());
5915 } catch (RemoteException e) {
5916 instrApp = null;
5917 }
5918 if (instrApp == null) {
5919 instrApp = new ApplicationInfo();
5920 }
Jeff Sharkey15447792015-11-05 16:18:51 -08005921 ii.copyTo(instrApp);
Fyodor Kupolovaf38b8e2015-12-02 16:16:07 -08005922 instrApp.initForUser(UserHandle.myUserId());
Todd Kennedy233a0b12018-01-29 20:30:24 +00005923 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07005924 appContext.getClassLoader(), false, true, false);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005925 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926
5927 try {
Alan Viverettebe64eae2015-09-03 14:56:04 -04005928 final ClassLoader cl = instrContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04005929 mInstrumentation = (Instrumentation)
5930 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 } catch (Exception e) {
5932 throw new RuntimeException(
5933 "Unable to instantiate instrumentation "
5934 + data.instrumentationName + ": " + e.toString(), e);
5935 }
5936
Alan Viverettebe64eae2015-09-03 14:56:04 -04005937 final ComponentName component = new ComponentName(ii.packageName, ii.name);
5938 mInstrumentation.init(this, instrContext, appContext, component,
5939 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005941 if (mProfiler.profileFile != null && !ii.handleProfiling
5942 && mProfiler.profileFd == null) {
5943 mProfiler.handlingProfiling = true;
Alan Viverettebe64eae2015-09-03 14:56:04 -04005944 final File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 file.getParentFile().mkdirs();
5946 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
5947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005948 } else {
5949 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05005950 mInstrumentation.basicInit(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 }
5952
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005953 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08005954 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Mathieu Chartier24cee072015-01-08 14:42:20 -08005955 } else {
5956 // Small heap, clamp to the current growth limit and let the heap release
5957 // pages after the growth limit to the non growth limit capacity. b/18387825
5958 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005959 }
5960
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005961 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08005962 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005963 // probably end up doing the same disk access.
Kurt Nelson5e154362017-06-29 17:20:56 -07005964 Application app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005965 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
Kurt Nelson571c3f62017-07-10 11:09:04 -07005966 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005968 // If the app is being launched for full backup or restore, bring it up in
5969 // a restricted environment with the base application class.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005970 app = data.info.makeApplication(data.restrictedBackupMode, null);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08005971
5972 // Propagate autofill compat state
5973 app.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);
5974
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005975 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005976
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005977 // don't bring up providers in restricted mode; they may depend on the
5978 // app's custom Application class
5979 if (!data.restrictedBackupMode) {
Jeff Sharkey3e195892016-03-05 19:48:59 -07005980 if (!ArrayUtils.isEmpty(data.providers)) {
5981 installContentProviders(app, data.providers);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005982 // For process that contains content providers, we want to
5983 // ensure that the JIT is enabled "at some point".
5984 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
5985 }
5986 }
5987
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005988 // Do this after providers, since instrumentation tests generally start their
5989 // test thread at this point, and we don't want that racing.
5990 try {
5991 mInstrumentation.onCreate(data.instrumentationArgs);
5992 }
5993 catch (Exception e) {
5994 throw new RuntimeException(
5995 "Exception thrown in onCreate() of "
5996 + data.instrumentationName + ": " + e.toString(), e);
5997 }
Kurt Nelson571c3f62017-07-10 11:09:04 -07005998 try {
5999 mInstrumentation.callApplicationOnCreate(app);
6000 } catch (Exception e) {
6001 if (!mInstrumentation.onException(app, e)) {
6002 throw new RuntimeException(
6003 "Unable to create application " + app.getClass().getName()
6004 + ": " + e.toString(), e);
6005 }
6006 }
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006007 } finally {
Kurt Nelson571c3f62017-07-10 11:09:04 -07006008 // If the app targets < O-MR1, or doesn't change the thread policy
6009 // during startup, clobber the policy to maintain behavior of b/36951662
Jeff Sharkeyaa1a9112018-04-10 15:18:12 -06006010 if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
Kurt Nelson571c3f62017-07-10 11:09:04 -07006011 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
6012 StrictMode.setThreadPolicy(savedPolicy);
Kurt Nelson5e154362017-06-29 17:20:56 -07006013 }
6014 }
6015
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006016 // Preload fonts resources
Seigo Nonaka54084b62017-04-24 14:46:23 -07006017 FontsContract.setApplicationContextForResources(appContext);
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006018 if (!Process.isIsolated()) {
6019 try {
6020 final ApplicationInfo info =
6021 getPackageManager().getApplicationInfo(
6022 data.appInfo.packageName,
6023 PackageManager.GET_META_DATA /*flags*/,
6024 UserHandle.myUserId());
6025 if (info.metaData != null) {
6026 final int preloadedFontsResource = info.metaData.getInt(
6027 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
6028 if (preloadedFontsResource != 0) {
6029 data.info.getResources().preloadFonts(preloadedFontsResource);
6030 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006031 }
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006032 } catch (RemoteException e) {
6033 throw e.rethrowFromSystemServer();
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006034 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 }
6037
6038 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006039 IActivityManager am = ActivityManager.getService();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006040 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
6041 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 Debug.stopMethodTracing();
6043 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006044 //Slog.i(TAG, "am: " + ActivityManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 // + ", app thr: " + mAppThread);
6046 try {
6047 am.finishInstrumentation(mAppThread, resultCode, results);
6048 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006049 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 }
6051 }
6052
Mathew Inwood4fb17d12018-08-14 14:25:44 +01006053 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07006054 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 Context context, List<ProviderInfo> providers) {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006056 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057
Romain Guya998dff2012-03-23 18:58:36 -07006058 for (ProviderInfo cpi : providers) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006059 if (DEBUG_PROVIDER) {
6060 StringBuilder buf = new StringBuilder(128);
6061 buf.append("Pub ");
6062 buf.append(cpi.authority);
6063 buf.append(": ");
6064 buf.append(cpi.name);
6065 Log.i(TAG, buf.toString());
6066 }
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006067 ContentProviderHolder cph = installProvider(context, null, cpi,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006068 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
6069 if (cph != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006070 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 }
6073 }
6074
6075 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006076 ActivityManager.getService().publishContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 getApplicationThread(), results);
6078 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006079 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 }
6081 }
6082
Mathew Inwood4fb17d12018-08-14 14:25:44 +01006083 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006084 public final IContentProvider acquireProvider(
6085 Context c, String auth, int userId, boolean stable) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006086 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006087 if (provider != null) {
6088 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 }
6090
Wale Ogunwale1d646122015-04-24 14:45:14 -07006091 // There is a possible race here. Another thread may try to acquire
6092 // the same provider at the same time. When this happens, we want to ensure
6093 // that the first one wins.
6094 // Note that we cannot hold the lock while acquiring and installing the
6095 // provider since it might take a long time to run and it could also potentially
6096 // be re-entrant in the case where the provider is in the same process.
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006097 ContentProviderHolder holder = null;
Wale Ogunwale1d646122015-04-24 14:45:14 -07006098 try {
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006099 synchronized (getGetProviderLock(auth, userId)) {
6100 holder = ActivityManager.getService().getContentProvider(
6101 getApplicationThread(), auth, userId, stable);
6102 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006103 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006104 throw ex.rethrowFromSystemServer();
Wale Ogunwale67fe0a42015-04-24 14:44:54 -07006105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 if (holder == null) {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006107 Slog.e(TAG, "Failed to find provider info for " + auth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 return null;
6109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006111 // Install provider will increment the reference count for us, and break
6112 // any ties in the race.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006113 holder = installProvider(c, holder, holder.info,
6114 true /*noisy*/, holder.noReleaseNeeded, stable);
6115 return holder.provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 }
6117
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006118 private Object getGetProviderLock(String auth, int userId) {
6119 final ProviderKey key = new ProviderKey(auth, userId);
6120 synchronized (mGetProviderLocks) {
6121 Object lock = mGetProviderLocks.get(key);
6122 if (lock == null) {
6123 lock = key;
6124 mGetProviderLocks.put(key, lock);
6125 }
6126 return lock;
6127 }
6128 }
6129
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006130 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
6131 if (stable) {
6132 prc.stableCount += 1;
6133 if (prc.stableCount == 1) {
6134 // We are acquiring a new stable reference on the provider.
6135 int unstableDelta;
6136 if (prc.removePending) {
6137 // We have a pending remove operation, which is holding the
6138 // last unstable reference. At this point we are converting
6139 // that unstable reference to our new stable reference.
6140 unstableDelta = -1;
6141 // Cancel the removal of the provider.
6142 if (DEBUG_PROVIDER) {
6143 Slog.v(TAG, "incProviderRef: stable "
6144 + "snatched provider from the jaws of death");
6145 }
6146 prc.removePending = false;
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006147 // There is a race! It fails to remove the message, which
6148 // will be handled in completeRemoveProvider().
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006149 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6150 } else {
6151 unstableDelta = 0;
6152 }
6153 try {
6154 if (DEBUG_PROVIDER) {
6155 Slog.v(TAG, "incProviderRef Now stable - "
6156 + prc.holder.info.name + ": unstableDelta="
6157 + unstableDelta);
6158 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006159 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006160 prc.holder.connection, 1, unstableDelta);
6161 } catch (RemoteException e) {
6162 //do nothing content provider object is dead any way
6163 }
6164 }
6165 } else {
6166 prc.unstableCount += 1;
6167 if (prc.unstableCount == 1) {
6168 // We are acquiring a new unstable reference on the provider.
6169 if (prc.removePending) {
6170 // Oh look, we actually have a remove pending for the
6171 // provider, which is still holding the last unstable
6172 // reference. We just need to cancel that to take new
6173 // ownership of the reference.
6174 if (DEBUG_PROVIDER) {
6175 Slog.v(TAG, "incProviderRef: unstable "
6176 + "snatched provider from the jaws of death");
6177 }
6178 prc.removePending = false;
6179 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6180 } else {
6181 // First unstable ref, increment our count in the
6182 // activity manager.
6183 try {
6184 if (DEBUG_PROVIDER) {
6185 Slog.v(TAG, "incProviderRef: Now unstable - "
6186 + prc.holder.info.name);
6187 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006188 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006189 prc.holder.connection, 0, 1);
6190 } catch (RemoteException e) {
6191 //do nothing content provider object is dead any way
6192 }
6193 }
6194 }
6195 }
6196 }
6197
Mathew Inwood4fb17d12018-08-14 14:25:44 +01006198 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006199 public final IContentProvider acquireExistingProvider(
6200 Context c, String auth, int userId, boolean stable) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006201 synchronized (mProviderMap) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006202 final ProviderKey key = new ProviderKey(auth, userId);
Jeff Sharkey6d515712012-09-20 16:06:08 -07006203 final ProviderClientRecord pr = mProviderMap.get(key);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006204 if (pr == null) {
6205 return null;
6206 }
6207
6208 IContentProvider provider = pr.mProvider;
6209 IBinder jBinder = provider.asBinder();
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006210 if (!jBinder.isBinderAlive()) {
6211 // The hosting process of the provider has died; we can't
6212 // use this one.
Wale Ogunwale1d646122015-04-24 14:45:14 -07006213 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006214 + ": existing object's process dead");
6215 handleUnstableProviderDiedLocked(jBinder, true);
6216 return null;
6217 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006218
6219 // Only increment the ref count if we have one. If we don't then the
6220 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006221 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006222 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006223 incProviderRefLocked(prc, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006224 }
6225 return provider;
6226 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006227 }
6228
Mathew Inwood4fb17d12018-08-14 14:25:44 +01006229 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006230 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
6231 if (provider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 return false;
6233 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006236 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006238 if (prc == null) {
6239 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006241 }
6242
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006243 boolean lastRef = false;
6244 if (stable) {
6245 if (prc.stableCount == 0) {
6246 if (DEBUG_PROVIDER) Slog.v(TAG,
6247 "releaseProvider: stable ref count already 0, how?");
6248 return false;
6249 }
6250 prc.stableCount -= 1;
6251 if (prc.stableCount == 0) {
6252 // What we do at this point depends on whether there are
6253 // any unstable refs left: if there are, we just tell the
6254 // activity manager to decrement its stable count; if there
6255 // aren't, we need to enqueue this provider to be removed,
6256 // and convert to holding a single unstable ref while
6257 // doing so.
6258 lastRef = prc.unstableCount == 0;
6259 try {
6260 if (DEBUG_PROVIDER) {
6261 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
6262 + lastRef + " - " + prc.holder.info.name);
6263 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006264 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006265 prc.holder.connection, -1, lastRef ? 1 : 0);
6266 } catch (RemoteException e) {
6267 //do nothing content provider object is dead any way
6268 }
6269 }
6270 } else {
6271 if (prc.unstableCount == 0) {
6272 if (DEBUG_PROVIDER) Slog.v(TAG,
6273 "releaseProvider: unstable ref count already 0, how?");
6274 return false;
6275 }
6276 prc.unstableCount -= 1;
6277 if (prc.unstableCount == 0) {
6278 // If this is the last reference, we need to enqueue
6279 // this provider to be removed instead of telling the
6280 // activity manager to remove it at this point.
6281 lastRef = prc.stableCount == 0;
6282 if (!lastRef) {
6283 try {
6284 if (DEBUG_PROVIDER) {
6285 Slog.v(TAG, "releaseProvider: No longer unstable - "
6286 + prc.holder.info.name);
6287 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006288 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006289 prc.holder.connection, 0, -1);
6290 } catch (RemoteException e) {
6291 //do nothing content provider object is dead any way
6292 }
6293 }
6294 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006295 }
6296
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006297 if (lastRef) {
6298 if (!prc.removePending) {
6299 // Schedule the actual remove asynchronously, since we don't know the context
6300 // this will be called in.
6301 // TODO: it would be nice to post a delayed message, so
6302 // if we come back and need the same provider quickly
6303 // we will still have it available.
6304 if (DEBUG_PROVIDER) {
6305 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
6306 + prc.holder.info.name);
6307 }
6308 prc.removePending = true;
6309 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
6310 mH.sendMessage(msg);
6311 } else {
6312 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
6313 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006314 }
6315 return true;
6316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 }
6318
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006319 final void completeRemoveProvider(ProviderRefCount prc) {
6320 synchronized (mProviderMap) {
6321 if (!prc.removePending) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006322 // There was a race! Some other client managed to acquire
6323 // the provider before the removal was completed.
6324 // Abort the removal. We will do it later.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006325 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006326 + "provider still in use");
6327 return;
6328 }
6329
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006330 // More complicated race!! Some client managed to acquire the
6331 // provider and release it before the removal was completed.
6332 // Continue the removal, and abort the next remove message.
6333 prc.removePending = false;
6334
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006335 final IBinder jBinder = prc.holder.provider.asBinder();
6336 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
6337 if (existingPrc == prc) {
6338 mProviderRefCountMap.remove(jBinder);
6339 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006340
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006341 for (int i=mProviderMap.size()-1; i>=0; i--) {
6342 ProviderClientRecord pr = mProviderMap.valueAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006343 IBinder myBinder = pr.mProvider.asBinder();
6344 if (myBinder == jBinder) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006345 mProviderMap.removeAt(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006346 }
6347 }
6348 }
6349
6350 try {
6351 if (DEBUG_PROVIDER) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006352 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006353 + "removeContentProvider(" + prc.holder.info.name + ")");
6354 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006355 ActivityManager.getService().removeContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006356 prc.holder.connection, false);
6357 } catch (RemoteException e) {
6358 //do nothing content provider object is dead any way
6359 }
6360 }
6361
Mathew Inwood4fb17d12018-08-14 14:25:44 +01006362 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006363 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006364 synchronized (mProviderMap) {
6365 handleUnstableProviderDiedLocked(provider, fromClient);
6366 }
6367 }
6368
6369 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
6370 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6371 if (prc != null) {
6372 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
6373 + provider + " " + prc.holder.info.name);
6374 mProviderRefCountMap.remove(provider);
You Kimbc74de62013-10-01 00:13:26 +09006375 for (int i=mProviderMap.size()-1; i>=0; i--) {
6376 ProviderClientRecord pr = mProviderMap.valueAt(i);
6377 if (pr != null && pr.mProvider.asBinder() == provider) {
6378 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
6379 mProviderMap.removeAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006380 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006381 }
You Kimbc74de62013-10-01 00:13:26 +09006382
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006383 if (fromClient) {
6384 // We found out about this due to execution in our client
6385 // code. Tell the activity manager about it now, to ensure
6386 // that the next time we go to do anything with the provider
6387 // it knows it is dead (so we don't race with its death
6388 // notification).
6389 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006390 ActivityManager.getService().unstableProviderDied(
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006391 prc.holder.connection);
6392 } catch (RemoteException e) {
6393 //do nothing content provider object is dead any way
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006394 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07006395 }
6396 }
6397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006399 final void appNotRespondingViaProvider(IBinder provider) {
6400 synchronized (mProviderMap) {
6401 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6402 if (prc != null) {
6403 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006404 ActivityManager.getService()
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006405 .appNotRespondingViaProvider(prc.holder.connection);
6406 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006407 throw e.rethrowFromSystemServer();
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006408 }
6409 }
6410 }
6411 }
6412
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006413 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006414 ContentProvider localProvider, ContentProviderHolder holder) {
Andreas Gampe18e99c12015-03-06 15:29:06 -08006415 final String auths[] = holder.info.authority.split(";");
Jeff Sharkey6d515712012-09-20 16:06:08 -07006416 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
6417
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006418 if (provider != null) {
6419 // If this provider is hosted by the core OS and cannot be upgraded,
6420 // then I guess we're okay doing blocking calls to it.
6421 for (String auth : auths) {
6422 switch (auth) {
6423 case ContactsContract.AUTHORITY:
6424 case CallLog.AUTHORITY:
6425 case CallLog.SHADOW_AUTHORITY:
6426 case BlockedNumberContract.AUTHORITY:
6427 case CalendarContract.AUTHORITY:
6428 case Downloads.Impl.AUTHORITY:
Jeff Sharkeycb621622016-11-11 14:04:32 -07006429 case "telephony":
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006430 Binder.allowBlocking(provider.asBinder());
6431 }
6432 }
6433 }
6434
Jeff Sharkey6d515712012-09-20 16:06:08 -07006435 final ProviderClientRecord pcr = new ProviderClientRecord(
6436 auths, provider, localProvider, holder);
6437 for (String auth : auths) {
6438 final ProviderKey key = new ProviderKey(auth, userId);
6439 final ProviderClientRecord existing = mProviderMap.get(key);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006440 if (existing != null) {
6441 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
Jeff Sharkey6d515712012-09-20 16:06:08 -07006442 + " already published as " + auth);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006443 } else {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006444 mProviderMap.put(key, pcr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 }
6446 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006447 return pcr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 }
6449
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006450 /**
6451 * Installs the provider.
6452 *
6453 * Providers that are local to the process or that come from the system server
6454 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
6455 * Other remote providers are reference counted. The initial reference count
6456 * for all reference counted providers is one. Providers that are not reference
6457 * counted do not have a reference count (at all).
6458 *
6459 * This method detects when a provider has already been installed. When this happens,
6460 * it increments the reference count of the existing provider (if appropriate)
6461 * and returns the existing provider. This can happen due to concurrent
6462 * attempts to acquire the same provider.
6463 */
Mathew Inwood4fb17d12018-08-14 14:25:44 +01006464 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006465 private ContentProviderHolder installProvider(Context context,
6466 ContentProviderHolder holder, ProviderInfo info,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006467 boolean noisy, boolean noReleaseNeeded, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 ContentProvider localProvider = null;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006469 IContentProvider provider;
Dianne Hackborn5f48fca2012-05-30 11:06:31 -07006470 if (holder == null || holder.provider == null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006471 if (DEBUG_PROVIDER || noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006472 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 + info.name);
6474 }
6475 Context c = null;
6476 ApplicationInfo ai = info.applicationInfo;
6477 if (context.getPackageName().equals(ai.packageName)) {
6478 c = context;
6479 } else if (mInitialApplication != null &&
6480 mInitialApplication.getPackageName().equals(ai.packageName)) {
6481 c = mInitialApplication;
6482 } else {
6483 try {
6484 c = context.createPackageContext(ai.packageName,
6485 Context.CONTEXT_INCLUDE_CODE);
6486 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07006487 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 }
6489 }
6490 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006491 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 ai.packageName +
6493 " while loading content provider " +
6494 info.name);
6495 return null;
6496 }
Adam Lesinski4e862812016-11-21 16:02:24 -08006497
6498 if (info.splitName != null) {
6499 try {
6500 c = c.createContextForSplit(info.splitName);
6501 } catch (NameNotFoundException e) {
6502 throw new RuntimeException(e);
6503 }
6504 }
6505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 try {
6507 final java.lang.ClassLoader cl = c.getClassLoader();
Todd Kennedy233a0b12018-01-29 20:30:24 +00006508 LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
6509 if (packageInfo == null) {
Jason Monka80bfb52017-11-16 17:15:37 -05006510 // System startup case.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006511 packageInfo = getSystemContext().mPackageInfo;
Jason Monka80bfb52017-11-16 17:15:37 -05006512 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00006513 localProvider = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05006514 .instantiateProvider(cl, info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 provider = localProvider.getIContentProvider();
6516 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006517 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 info.name + " from sourceDir " +
6519 info.applicationInfo.sourceDir);
6520 return null;
6521 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006522 if (DEBUG_PROVIDER) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 TAG, "Instantiating local provider " + info.name);
6524 // XXX Need to create the correct context for this provider.
6525 localProvider.attachInfo(c, info);
6526 } catch (java.lang.Exception e) {
6527 if (!mInstrumentation.onException(null, e)) {
6528 throw new RuntimeException(
6529 "Unable to get provider " + info.name
6530 + ": " + e.toString(), e);
6531 }
6532 return null;
6533 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006534 } else {
6535 provider = holder.provider;
6536 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 + info.name);
6538 }
6539
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006540 ContentProviderHolder retHolder;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006541
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006542 synchronized (mProviderMap) {
6543 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
6544 + " / " + info.name);
6545 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 if (localProvider != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006547 ComponentName cname = new ComponentName(info.packageName, info.name);
6548 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006549 if (pr != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006550 if (DEBUG_PROVIDER) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006551 Slog.v(TAG, "installProvider: lost the race, "
6552 + "using existing local provider");
6553 }
6554 provider = pr.mProvider;
6555 } else {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006556 holder = new ContentProviderHolder(info);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006557 holder.provider = provider;
6558 holder.noReleaseNeeded = true;
6559 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006560 mLocalProviders.put(jBinder, pr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006561 mLocalProvidersByName.put(cname, pr);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006562 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006563 retHolder = pr.mHolder;
6564 } else {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006565 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
6566 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006567 if (DEBUG_PROVIDER) {
6568 Slog.v(TAG, "installProvider: lost the race, updating ref count");
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006569 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006570 // We need to transfer our new reference to the existing
6571 // ref count, releasing the old one... but only if
6572 // release is needed (that is, it is not running in the
6573 // system process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006574 if (!noReleaseNeeded) {
6575 incProviderRefLocked(prc, stable);
Wale Ogunwale1d646122015-04-24 14:45:14 -07006576 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006577 ActivityManager.getService().removeContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07006578 holder.connection, stable);
6579 } catch (RemoteException e) {
6580 //do nothing content provider object is dead any way
6581 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006582 }
6583 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006584 ProviderClientRecord client = installProviderAuthoritiesLocked(
6585 provider, localProvider, holder);
6586 if (noReleaseNeeded) {
6587 prc = new ProviderRefCount(holder, client, 1000, 1000);
6588 } else {
6589 prc = stable
6590 ? new ProviderRefCount(holder, client, 1, 0)
6591 : new ProviderRefCount(holder, client, 0, 1);
6592 }
6593 mProviderRefCountMap.put(jBinder, prc);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006594 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006595 retHolder = prc.holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 }
6597 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006598 return retHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 }
6600
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04006601 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
6602 try {
6603 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
6604 main.invoke(null, new Object[]{entryPointArgs});
6605 } catch (ReflectiveOperationException e) {
6606 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
6607 }
6608 // The process will be empty after this method returns; exit the VM now.
6609 System.exit(0);
6610 }
6611
Mathew Inwood4fb17d12018-08-14 14:25:44 +01006612 @UnsupportedAppUsage
Sudheer Shankaf6690102017-10-16 10:20:32 -07006613 private void attach(boolean system, long startSeq) {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08006614 sCurrentActivityThread = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006617 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Craig Mautner88c05892013-06-28 09:47:45 -07006618 @Override
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08006619 public void run() {
6620 ensureJitEnabled();
6621 }
6622 });
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006623 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
6624 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 RuntimeInit.setApplicationObject(mAppThread.asBinder());
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006626 final IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 try {
Sudheer Shankaf6690102017-10-16 10:20:32 -07006628 mgr.attachApplication(mAppThread, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006630 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006632 // Watch for getting close to heap limit.
6633 BinderInternal.addGcWatcher(new Runnable() {
6634 @Override public void run() {
6635 if (!mSomeActivitiesChanged) {
6636 return;
6637 }
6638 Runtime runtime = Runtime.getRuntime();
6639 long dalvikMax = runtime.maxMemory();
6640 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
6641 if (dalvikUsed > ((3*dalvikMax)/4)) {
6642 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
6643 + " total=" + (runtime.totalMemory()/1024)
6644 + " used=" + (dalvikUsed/1024));
6645 mSomeActivitiesChanged = false;
6646 try {
6647 mgr.releaseSomeActivities(mAppThread);
6648 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006649 throw e.rethrowFromSystemServer();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006650 }
6651 }
6652 }
6653 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 } else {
6655 // Don't set application object here -- if the system crashes,
6656 // we can't display an alert, we just want to die die die.
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006657 android.ddm.DdmHandleAppName.setAppName("system_process",
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006658 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 try {
6660 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05006661 mInstrumentation.basicInit(this);
Jeff Browndefd4a62014-03-10 21:24:37 -07006662 ContextImpl context = ContextImpl.createAppContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00006663 this, getSystemContext().mPackageInfo);
6664 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
Jeff Brown7fc8e352014-09-16 18:06:47 -07006665 mInitialApplication.onCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 } catch (Exception e) {
6667 throw new RuntimeException(
6668 "Unable to instantiate Application():" + e.toString(), e);
6669 }
6670 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006671
Andrii Kulian44607962017-03-16 11:06:24 -07006672 ViewRootImpl.ConfigChangedCallback configChangedCallback
6673 = (Configuration globalConfig) -> {
6674 synchronized (mResourcesManager) {
6675 // We need to apply this change to the resources immediately, because upon returning
6676 // the view hierarchy will be informed about it.
6677 if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
6678 null /* compat */)) {
6679 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
6680 mResourcesManager.getConfiguration().getLocales());
Adam Lesinskib61e4052016-05-19 18:23:05 -07006681
Andrii Kulian44607962017-03-16 11:06:24 -07006682 // This actually changed the resources! Tell everyone about it.
6683 if (mPendingConfiguration == null
6684 || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
6685 mPendingConfiguration = globalConfig;
6686 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006687 }
6688 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006689 }
Andrii Kulian44607962017-03-16 11:06:24 -07006690 };
6691 ViewRootImpl.addConfigCallback(configChangedCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 }
6693
Mathew Inwood4fb17d12018-08-14 14:25:44 +01006694 @UnsupportedAppUsage
Romain Guy5e9120d2012-01-30 12:17:22 -08006695 public static ActivityThread systemMain() {
Alan Viverette5e1565e2014-07-29 16:14:25 -07006696 // The system process on low-memory devices do not get to use hardware
6697 // accelerated drawing, since this can add too much overhead to the
6698 // process.
6699 if (!ActivityManager.isHighEndGfx()) {
John Reck51aaf902015-12-02 15:08:07 -08006700 ThreadedRenderer.disable(true);
John Reck73840ea2014-09-22 07:39:18 -07006701 } else {
John Reck51aaf902015-12-02 15:08:07 -08006702 ThreadedRenderer.enableForegroundTrimming();
Alan Viverette5e1565e2014-07-29 16:14:25 -07006703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07006705 thread.attach(true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 return thread;
6707 }
6708
Mathew Inwood4fb17d12018-08-14 14:25:44 +01006709 @UnsupportedAppUsage
Jeff Brown10e89712011-07-08 18:52:57 -07006710 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07006712 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 }
6714 }
6715
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006716 public int getIntCoreSetting(String key, int defaultValue) {
Craig Mautner88c05892013-06-28 09:47:45 -07006717 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08006718 if (mCoreSettings != null) {
6719 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006720 }
Craig Mautner88c05892013-06-28 09:47:45 -07006721 return defaultValue;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006722 }
6723 }
6724
Romain Guy65b345f2011-07-27 18:51:50 -07006725 public static void main(String[] args) {
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006726 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
Bob Leee5408332009-09-04 18:31:17 -07006727
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08006728 // CloseGuard defaults to true and can be quite spammy. We
6729 // disable it here, but selectively enable it later (via
6730 // StrictMode) on debug builds, but using DropBox, not logs.
6731 CloseGuard.setEnabled(false);
6732
Andreas Gamped281b422016-07-08 03:50:27 +00006733 Environment.initForCurrentUser();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006734
Robin Lee3d076af2014-04-25 14:57:49 +01006735 // Make sure TrustedCertificateStore looks in the right place for CA certificates
6736 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
6737 TrustedCertificateStore.setDefaultUserDirectory(configDir);
6738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 Process.setArgV0("<pre-initialized>");
6740
6741 Looper.prepareMainLooper();
6742
Sudheer Shankaf6690102017-10-16 10:20:32 -07006743 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
6744 // It will be in the format "seq=114"
6745 long startSeq = 0;
6746 if (args != null) {
6747 for (int i = args.length - 1; i >= 0; --i) {
6748 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
6749 startSeq = Long.parseLong(
6750 args[i].substring(PROC_START_SEQ_IDENT.length()));
6751 }
6752 }
6753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07006755 thread.attach(false, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756
Vairavan Srinivasan7335cfd2012-08-18 18:36:03 -07006757 if (sMainThreadHandler == null) {
6758 sMainThreadHandler = thread.getHandler();
6759 }
6760
Dianne Hackborn287952c2010-09-22 22:34:31 -07006761 if (false) {
6762 Looper.myLooper().setMessageLogging(new
6763 LogPrinter(Log.DEBUG, "ActivityThread"));
6764 }
6765
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006766 // End of event ActivityThreadMain.
6767 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 Looper.loop();
6769
Jeff Brown10e89712011-07-08 18:52:57 -07006770 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 }
Chris Craikfc294242016-12-13 18:10:46 -08006772
6773 // ------------------ Regular JNI ------------------------
Tim Murray12f511e2018-10-22 15:26:08 -07006774 private native void nPurgePendingResources();
Chris Craikfc294242016-12-13 18:10:46 -08006775 private native void nDumpGraphicsInfo(FileDescriptor fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776}