blob: 4d627e070a3878922c236ccc0ac3febba374b195 [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;
Dianne Hackborn69c6adc2015-06-02 10:52:59 -070030import android.app.assist.AssistContent;
31import android.app.assist.AssistStructure;
Christopher Tate45281862010-03-05 15:46:30 -080032import android.app.backup.BackupAgent;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080033import android.app.servertransaction.ActivityLifecycleItem.LifecycleState;
Andrii Kulian446e8242017-10-26 15:17:29 -070034import android.app.servertransaction.ActivityResultItem;
35import android.app.servertransaction.ClientTransaction;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080036import android.app.servertransaction.PendingTransactionActions;
37import android.app.servertransaction.PendingTransactionActions.StopInfo;
38import android.app.servertransaction.TransactionExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070040import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ComponentName;
42import android.content.ContentProvider;
43import android.content.Context;
44import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070045import android.content.IIntentReceiver;
Jesse Hall317fa5a2017-05-23 15:46:55 -070046import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.ActivityInfo;
48import android.content.pm.ApplicationInfo;
49import android.content.pm.IPackageManager;
50import android.content.pm.InstrumentationInfo;
Christopher Tate346acb12012-10-15 19:20:25 -070051import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070053import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070054import android.content.pm.ParceledListSlice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.ProviderInfo;
56import android.content.pm.ServiceInfo;
57import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070058import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.res.Configuration;
60import android.content.res.Resources;
Alan Viverettee54d2452015-05-06 10:41:43 -070061import android.content.res.Resources.Theme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.database.sqlite.SQLiteDatabase;
63import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080064import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.graphics.Bitmap;
66import android.graphics.Canvas;
Jeff Brownbd6e1502012-08-28 03:27:37 -070067import android.hardware.display.DisplayManagerGlobal;
Paul Jensene0bef712014-12-10 15:12:18 -050068import android.net.ConnectivityManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.IConnectivityManager;
Paul Jensene0bef712014-12-10 15:12:18 -050070import android.net.Network;
Robert Greenwalt434203a2010-10-11 16:00:27 -070071import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040072import android.net.ProxyInfo;
Jason Monk83520b92014-05-09 15:16:06 -040073import android.net.Uri;
Joe Onoratod630f102011-03-17 18:42:26 -070074import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070075import android.os.Binder;
Jeff Sharkey344744b2016-01-28 19:03:30 -070076import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Bundle;
78import android.os.Debug;
Geremy Condrab7faaf42012-09-19 18:07:42 -070079import android.os.DropBoxManager;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070080import android.os.Environment;
Jesse Hallb12249b2016-12-12 12:53:02 -080081import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Handler;
Jeff Sharkey8439ac02017-12-12 17:26:23 -070083import android.os.HandlerExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.IBinder;
Adam Lesinskib61e4052016-05-19 18:23:05 -070085import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Looper;
87import android.os.Message;
88import android.os.MessageQueue;
Dianne Hackbornfabb70b2014-11-11 12:22:36 -080089import android.os.Parcel;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070090import android.os.ParcelFileDescriptor;
Craig Mautnera0026042014-04-23 11:45:37 -070091import android.os.PersistableBundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.Process;
93import android.os.RemoteException;
94import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070095import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.SystemClock;
Jeff Brownefd43bd2012-09-21 17:02:35 -070097import android.os.SystemProperties;
Dianne Hackborn1ded0b12012-04-26 14:14:50 -070098import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070099import android.os.UserHandle;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600100import android.provider.BlockedNumberContract;
101import android.provider.CalendarContract;
102import android.provider.CallLog;
103import android.provider.ContactsContract;
104import android.provider.Downloads;
Seigo Nonaka54084b62017-04-24 14:46:23 -0700105import android.provider.FontsContract;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000106import android.provider.Settings;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700107import android.renderscript.RenderScriptCacheDir;
Chad Brubakerc72875b2016-04-27 16:35:11 -0700108import android.security.NetworkSecurityPolicy;
Chad Brubaker78d47122015-11-17 22:26:58 -0800109import android.security.net.config.NetworkSecurityConfigProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.util.AndroidRuntimeException;
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700111import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.util.DisplayMetrics;
113import android.util.EventLog;
114import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700115import android.util.LogPrinter;
Craig Mautnereb8abf72014-07-02 15:04:09 -0700116import android.util.Pair;
Jeff Brown6754ba22011-12-14 20:20:01 -0800117import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800118import android.util.Slog;
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700119import android.util.SparseIntArray;
Adam Powell14874662013-07-18 19:42:41 -0700120import android.util.SuperNotCalledException;
Kweku Adams598e9a22017-11-02 17:12:20 -0700121import android.util.proto.ProtoOutputStream;
Adam Lesinski3ad1b482016-04-01 16:41:41 -0700122import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.view.Display;
John Reck51aaf902015-12-02 15:08:07 -0800124import android.view.ThreadedRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import android.view.View;
126import android.view.ViewDebug;
127import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -0700128import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.view.Window;
130import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700131import android.view.WindowManagerGlobal;
Richard Uhler2c036192016-09-14 09:48:31 +0100132import android.webkit.WebView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700134import com.android.internal.annotations.GuardedBy;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800135import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700136import com.android.internal.app.IVoiceInteractor;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800137import com.android.internal.content.ReferrerIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import com.android.internal.os.BinderInternal;
139import com.android.internal.os.RuntimeInit;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700140import com.android.internal.os.SomeArgs;
Jeff Sharkey3e195892016-03-05 19:48:59 -0700141import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -0700142import com.android.internal.util.FastPrintWriter;
Kenny Root12e75222013-04-23 22:34:24 -0700143import com.android.org.conscrypt.OpenSSLSocketImpl;
Robin Lee3d076af2014-04-25 14:57:49 +0100144import com.android.org.conscrypt.TrustedCertificateStore;
Kweku Adams598e9a22017-11-02 17:12:20 -0700145import com.android.server.am.proto.MemInfoProto;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700146
147import dalvik.system.BaseDexClassLoader;
148import dalvik.system.CloseGuard;
149import dalvik.system.VMDebug;
150import dalvik.system.VMRuntime;
151
Jesse Hall317fa5a2017-05-23 15:46:55 -0700152import libcore.io.DropBox;
153import libcore.io.EventLogger;
154import libcore.io.IoUtils;
155import libcore.net.event.NetworkEventDispatcher;
156
157import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159import java.io.File;
160import java.io.FileDescriptor;
161import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700162import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163import java.io.PrintWriter;
164import java.lang.ref.WeakReference;
Svet Ganov37e43272016-09-09 16:01:32 -0700165import java.lang.reflect.Field;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400166import java.lang.reflect.Method;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700167import java.net.InetAddress;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000168import java.text.DateFormat;
Bryce Leed946f862018-01-16 15:59:47 -0800169import java.util.ArrayDeque;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170import java.util.ArrayList;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600171import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172import java.util.List;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700173import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174import java.util.Map;
Kenny Roote6585b32013-12-13 12:00:26 -0800175import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176import java.util.TimeZone;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700177import java.util.concurrent.Executor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700179final class RemoteServiceException extends AndroidRuntimeException {
180 public RemoteServiceException(String msg) {
181 super(msg);
182 }
183}
184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185/**
186 * This manages the execution of the main thread in an
187 * application process, scheduling and executing activities,
188 * broadcasts, and other operations on it as the activity
189 * manager requests.
190 *
191 * {@hide}
192 */
Andrii Kulian446e8242017-10-26 15:17:29 -0700193public final class ActivityThread extends ClientTransactionHandler {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700194 /** @hide */
195 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700196 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700197 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700198 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700199 /** @hide */
200 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700201 private static final boolean DEBUG_RESULTS = false;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700202 private static final boolean DEBUG_BACKUP = false;
Craig Mautner88c05892013-06-28 09:47:45 -0700203 public static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800204 private static final boolean DEBUG_SERVICE = false;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800205 public static final boolean DEBUG_MEMORY_TRIM = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700206 private static final boolean DEBUG_PROVIDER = false;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700207 private static final boolean DEBUG_ORDER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
Craig Mautnere3119b72015-01-20 15:02:36 -0800210 private static final int LOG_AM_ON_PAUSE_CALLED = 30021;
211 private static final int LOG_AM_ON_RESUME_CALLED = 30022;
Wale Ogunwalecd7043e2016-02-27 17:37:46 -0800212 private static final int LOG_AM_ON_STOP_CALLED = 30049;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Dianne Hackborn455625e2015-01-21 09:55:13 -0800214 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
215 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
216 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
217 public static final int SERVICE_DONE_EXECUTING_START = 1;
218 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
219 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
220
Filip Gruszczynskica664812015-12-04 12:43:36 -0800221 // Whether to invoke an activity callback after delivering new configuration.
222 private static final boolean REPORT_TO_ACTIVITY = true;
223
Bryce Leed946f862018-01-16 15:59:47 -0800224 // Maximum number of recent tokens to maintain for debugging purposes
225 private static final int MAX_RECENT_TOKENS = 10;
226
Sudheer Shanka84a48952017-03-08 18:19:01 -0800227 /**
228 * Denotes an invalid sequence number corresponding to a process state change.
229 */
230 public static final long INVALID_PROC_STATE_SEQ = -1;
231
Sudheer Shankaf6690102017-10-16 10:20:32 -0700232 /**
233 * Identifier for the sequence no. associated with this process start. It will be provided
234 * as one of the arguments when the process starts.
235 */
236 public static final String PROC_START_SEQ_IDENT = "seq=";
237
Sudheer Shanka84a48952017-03-08 18:19:01 -0800238 private final Object mNetworkPolicyLock = new Object();
239
240 /**
241 * Denotes the sequence number of the process state change for which the main thread needs
242 * to block until the network rules are updated for it.
243 *
244 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
245 */
246 @GuardedBy("mNetworkPolicyLock")
247 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
248
Jeff Browndefd4a62014-03-10 21:24:37 -0700249 private ContextImpl mSystemContext;
Adam Lesinskia82b6262017-03-21 16:56:17 -0700250 private ContextImpl mSystemUiContext;
Bob Leee5408332009-09-04 18:31:17 -0700251
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700252 static volatile IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700254 final ApplicationThread mAppThread = new ApplicationThread();
255 final Looper mLooper = Looper.myLooper();
256 final H mH = new H();
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700257 final Executor mExecutor = new HandlerExecutor(mH);
Dianne Hackborn782d4982015-07-08 17:36:37 -0700258 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
Bryce Leed946f862018-01-16 15:59:47 -0800259 final ArrayDeque<Integer> mRecentTokens = new ArrayDeque<>();
260
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.
265 int mNumVisibleActivities = 0;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700266 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
267 private int mLastSessionId;
Dianne Hackborn782d4982015-07-08 17:36:37 -0700268 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700269 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700270 Profiler mProfiler;
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700271 int mCurDefaultDisplayDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -0700272 boolean mDensityCompatMode;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700273 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700274 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700275 Application mInitialApplication;
276 final ArrayList<Application> mAllApplications
277 = new ArrayList<Application>();
278 // set of instantiated backup agents, keyed by package name
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700279 final ArrayMap<String, BackupAgent> mBackupAgents = new ArrayMap<String, BackupAgent>();
Jeff Sharkey66a017b2013-01-17 18:18:22 -0800280 /** Reference to singleton {@link ActivityThread} */
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700281 private static volatile ActivityThread sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700282 Instrumentation mInstrumentation;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700283 String mInstrumentationPackageName = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700284 String mInstrumentationAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700285 String[] mInstrumentationSplitAppDirs = null;
286 String mInstrumentationLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700287 String mInstrumentedAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700288 String[] mInstrumentedSplitAppDirs = null;
289 String mInstrumentedLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700290 boolean mSystemThread = false;
291 boolean mJitEnabled = false;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700292 boolean mSomeActivitiesChanged = false;
Chong Zhang4951f9d2016-06-23 13:15:08 -0700293 boolean mUpdatingSystemConfig = false;
David Brazdild960cc42018-01-31 07:59:17 +0000294 /* package */ boolean mHiddenApiWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100296 // These can be accessed by multiple threads; mResourcesManager is the lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700297 // XXX For now we keep around information about all packages we have
298 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800299 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700300 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800301 // which means this lock gets held while the activity and window managers
302 // holds their own lock. Thus you MUST NEVER call back into the activity manager
303 // or window manager or anything that depends on them while holding this lock.
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700304 // These LoadedApk are only valid for the userId that we're running as.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100305 @GuardedBy("mResourcesManager")
306 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
307 @GuardedBy("mResourcesManager")
308 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
309 @GuardedBy("mResourcesManager")
310 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
311 @GuardedBy("mResourcesManager")
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700312 Configuration mPendingConfiguration = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800313 // An executor that performs multi-step transactions.
314 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315
Craig Mautner88c05892013-06-28 09:47:45 -0700316 private final ResourcesManager mResourcesManager;
317
Jeff Sharkey6d515712012-09-20 16:06:08 -0700318 private static final class ProviderKey {
319 final String authority;
320 final int userId;
321
322 public ProviderKey(String authority, int userId) {
323 this.authority = authority;
324 this.userId = userId;
325 }
326
327 @Override
328 public boolean equals(Object o) {
329 if (o instanceof ProviderKey) {
330 final ProviderKey other = (ProviderKey) o;
Kenny Roote6585b32013-12-13 12:00:26 -0800331 return Objects.equals(authority, other.authority) && userId == other.userId;
Jeff Sharkey6d515712012-09-20 16:06:08 -0700332 }
333 return false;
334 }
335
336 @Override
337 public int hashCode() {
338 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
339 }
340 }
341
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700342 // The lock of mProviderMap protects the following variables.
Wale Ogunwale1d646122015-04-24 14:45:14 -0700343 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
344 = new ArrayMap<ProviderKey, ProviderClientRecord>();
345 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
346 = new ArrayMap<IBinder, ProviderRefCount>();
347 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
348 = new ArrayMap<IBinder, ProviderClientRecord>();
349 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
350 = new ArrayMap<ComponentName, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700352 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
Wale Ogunwale1d646122015-04-24 14:45:14 -0700353 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
Jeff Hamilton52d32032011-01-08 15:31:26 -0600354
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700355 final GcIdler mGcIdler = new GcIdler();
356 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700358 static volatile Handler sMainThreadHandler; // set once in main()
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700359
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800360 Bundle mCoreSettings = null;
361
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800362 /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
363 public static final class ActivityClientRecord {
364 public IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700365 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 Intent intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800367 String referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700368 IVoiceInteractor voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -0700370 PersistableBundle persistentState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 Activity activity;
372 Window window;
373 Activity parent;
374 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700375 Activity.NonConfigurationInstances lastNonConfigurationInstances;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800376 // TODO(lifecycler): Use mLifecycleState instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 boolean paused;
378 boolean stopped;
379 boolean hideForNow;
380 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700381 Configuration createdConfig;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800382 Configuration overrideConfig;
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800383 // Used for consolidating configs before sending on to Activity.
384 private Configuration tmpConfig = new Configuration();
Andrii Kulian44607962017-03-16 11:06:24 -0700385 // Callback used for updating activity override config.
386 ViewRootImpl.ActivityConfigCallback configCallback;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700387 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388
Jeff Hao1b012d32014-08-20 10:35:34 -0700389 ProfilerInfo profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400392 CompatibilityInfo compatInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000393 public LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394
395 List<ResultInfo> pendingResults;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800396 List<ReferrerIntent> pendingIntents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397
398 boolean startsNotResumed;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800399 public final boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800400 int pendingConfigChanges;
401 boolean onlyLocalRequest;
402
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700403 Window mPendingRemoveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800404 WindowManager mPendingRemoveWindowManager;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700405 boolean mPreserveWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800407 @LifecycleState
408 private int mLifecycleState = PRE_ON_CREATE;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700409
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800410 @VisibleForTesting
411 public ActivityClientRecord() {
412 this.isForward = false;
413 init();
414 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700415
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800416 public ActivityClientRecord(IBinder token, Intent intent, int ident,
417 ActivityInfo info, Configuration overrideConfig, CompatibilityInfo compatInfo,
418 String referrer, IVoiceInteractor voiceInteractor, Bundle state,
419 PersistableBundle persistentState, List<ResultInfo> pendingResults,
420 List<ReferrerIntent> pendingNewIntents, boolean isForward,
421 ProfilerInfo profilerInfo, ClientTransactionHandler client) {
422 this.token = token;
423 this.ident = ident;
424 this.intent = intent;
425 this.referrer = referrer;
426 this.voiceInteractor = voiceInteractor;
427 this.activityInfo = info;
428 this.compatInfo = compatInfo;
429 this.state = state;
430 this.persistentState = persistentState;
431 this.pendingResults = pendingResults;
432 this.pendingIntents = pendingNewIntents;
433 this.isForward = isForward;
434 this.profilerInfo = profilerInfo;
435 this.overrideConfig = overrideConfig;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000436 this.packageInfo = client.getPackageInfoNoCheck(activityInfo.applicationInfo,
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800437 compatInfo);
438 init();
439 }
440
441 /** Common initializer for all constructors. */
442 private void init() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 parent = null;
444 embeddedID = null;
445 paused = false;
446 stopped = false;
447 hideForNow = false;
448 nextIdle = null;
Andrii Kulian44607962017-03-16 11:06:24 -0700449 configCallback = (Configuration overrideConfig, int newDisplayId) -> {
450 if (activity == null) {
451 throw new IllegalStateException(
452 "Received config update for non-existing activity");
453 }
Andrii Kulian446e8242017-10-26 15:17:29 -0700454 activity.mMainThread.handleActivityConfigurationChanged(token, overrideConfig,
455 newDisplayId);
Andrii Kulian44607962017-03-16 11:06:24 -0700456 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 }
458
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800459 /** Get the current lifecycle state. */
460 public int getLifecycleState() {
461 return mLifecycleState;
462 }
463
464 /** Update the current lifecycle state for internal bookkeeping. */
465 public void setState(@LifecycleState int newLifecycleState) {
466 mLifecycleState = newLifecycleState;
467 switch (mLifecycleState) {
468 case ON_CREATE:
469 paused = true;
470 stopped = true;
471 break;
472 case ON_START:
473 paused = true;
474 stopped = false;
475 break;
476 case ON_RESUME:
477 paused = false;
478 stopped = false;
479 break;
480 case ON_PAUSE:
481 paused = true;
482 stopped = false;
483 break;
484 case ON_STOP:
485 paused = true;
486 stopped = true;
487 break;
488 }
489 }
490
Andrii Kulian391161f2018-01-29 10:50:02 -0800491 private boolean isPreHoneycomb() {
492 return activity != null && activity.getApplicationInfo().targetSdkVersion
493 < android.os.Build.VERSION_CODES.HONEYCOMB;
494 }
495
496 private boolean isPreP() {
497 return activity != null && activity.getApplicationInfo().targetSdkVersion
498 < android.os.Build.VERSION_CODES.P;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800499 }
500
Craig Mautnera0026042014-04-23 11:45:37 -0700501 public boolean isPersistable() {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700502 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
Craig Mautnera0026042014-04-23 11:45:37 -0700503 }
504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 public String toString() {
Dianne Hackbornb61a0262012-05-14 17:19:18 -0700506 ComponentName componentName = intent != null ? intent.getComponent() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 return "ActivityRecord{"
508 + Integer.toHexString(System.identityHashCode(this))
509 + " token=" + token + " " + (componentName == null
510 ? "no component name" : componentName.toShortString())
511 + "}";
512 }
Andrii Kulian58178f22016-03-16 13:44:56 -0700513
514 public String getStateString() {
515 StringBuilder sb = new StringBuilder();
516 sb.append("ActivityClientRecord{");
517 sb.append("paused=").append(paused);
518 sb.append(", stopped=").append(stopped);
519 sb.append(", hideForNow=").append(hideForNow);
520 sb.append(", startsNotResumed=").append(startsNotResumed);
521 sb.append(", isForward=").append(isForward);
522 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
523 sb.append(", onlyLocalRequest=").append(onlyLocalRequest);
524 sb.append(", preserveWindow=").append(mPreserveWindow);
525 if (activity != null) {
526 sb.append(", Activity{");
527 sb.append("resumed=").append(activity.mResumed);
528 sb.append(", stopped=").append(activity.mStopped);
529 sb.append(", finished=").append(activity.isFinishing());
530 sb.append(", destroyed=").append(activity.isDestroyed());
531 sb.append(", startedActivity=").append(activity.mStartedActivity);
532 sb.append(", temporaryPause=").append(activity.mTemporaryPause);
533 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
Andrii Kulian58178f22016-03-16 13:44:56 -0700534 sb.append("}");
535 }
536 sb.append("}");
537 return sb.toString();
538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 }
540
Wale Ogunwale1d646122015-04-24 14:45:14 -0700541 final class ProviderClientRecord {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700542 final String[] mNames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 final IContentProvider mProvider;
544 final ContentProvider mLocalProvider;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700545 final ContentProviderHolder mHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700547 ProviderClientRecord(String[] names, IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700548 ContentProvider localProvider, ContentProviderHolder holder) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700549 mNames = names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 mProvider = provider;
551 mLocalProvider = localProvider;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700552 mHolder = holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 }
554 }
555
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400556 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700557 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700558 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
559 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
riddle_hsu1f5ac4d2015-01-03 15:38:21 +0800560 token, sendingUser, intent.getFlags());
Dianne Hackborne829fef2010-10-26 17:44:01 -0700561 this.intent = intent;
562 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 Intent intent;
565 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400566 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 public String toString() {
568 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700569 info.packageName + " resultCode=" + getResultCode()
570 + " resultData=" + getResultData() + " resultExtras="
571 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
573 }
574
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400575 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700576 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400577 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700578 int backupMode;
579 public String toString() {
580 return "CreateBackupAgentData{appInfo=" + appInfo
581 + " backupAgent=" + appInfo.backupAgentName
582 + " mode=" + backupMode + "}";
583 }
584 }
Bob Leee5408332009-09-04 18:31:17 -0700585
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400586 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 IBinder token;
588 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400589 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 Intent intent;
591 public String toString() {
592 return "CreateServiceData{token=" + token + " className="
593 + info.name + " packageName=" + info.packageName
594 + " intent=" + intent + "}";
595 }
596 }
597
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400598 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 IBinder token;
600 Intent intent;
601 boolean rebind;
602 public String toString() {
603 return "BindServiceData{token=" + token + " intent=" + intent + "}";
604 }
605 }
606
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400607 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700609 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700611 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 Intent args;
613 public String toString() {
614 return "ServiceArgsData{token=" + token + " startId=" + startId
615 + " args=" + args + "}";
616 }
617 }
618
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400619 static final class AppBindData {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000620 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 String processName;
622 ApplicationInfo appInfo;
623 List<ProviderInfo> providers;
624 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 Bundle instrumentationArgs;
626 IInstrumentationWatcher instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800627 IUiAutomationConnection instrumentationUiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 int debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400629 boolean enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700630 boolean trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -0700631 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700632 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400634 CompatibilityInfo compatInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700635 String buildSerial;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700636
637 /** Initial values for {@link Profiler}. */
Jeff Hao1b012d32014-08-20 10:35:34 -0700638 ProfilerInfo initProfilerInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700639
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800640 boolean autofillCompatibilityEnabled;
641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 public String toString() {
643 return "AppBindData{appInfo=" + appInfo + "}";
644 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700645 }
646
647 static final class Profiler {
648 String profileFile;
649 ParcelFileDescriptor profileFd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700650 int samplingInterval;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700651 boolean autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800652 boolean streamingOutput;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700653 boolean profiling;
654 boolean handlingProfiling;
Jeff Hao1b012d32014-08-20 10:35:34 -0700655 public void setProfiler(ProfilerInfo profilerInfo) {
656 ParcelFileDescriptor fd = profilerInfo.profileFd;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700657 if (profiling) {
658 if (fd != null) {
659 try {
660 fd.close();
661 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700662 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700663 }
664 }
665 return;
666 }
667 if (profileFd != null) {
668 try {
669 profileFd.close();
670 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700671 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700672 }
673 }
Jeff Hao1b012d32014-08-20 10:35:34 -0700674 profileFile = profilerInfo.profileFile;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700675 profileFd = fd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700676 samplingInterval = profilerInfo.samplingInterval;
677 autoStopProfiler = profilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800678 streamingOutput = profilerInfo.streamingOutput;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700679 }
680 public void startProfiling() {
681 if (profileFd == null || profiling) {
682 return;
683 }
684 try {
Andreas Gampeeff06392016-05-10 12:51:45 -0700685 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
Jeff Hao1b012d32014-08-20 10:35:34 -0700686 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800687 bufferSize * 1024 * 1024, 0, samplingInterval != 0, samplingInterval,
688 streamingOutput);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700689 profiling = true;
690 } catch (RuntimeException e) {
691 Slog.w(TAG, "Profiling failed on path " + profileFile);
692 try {
693 profileFd.close();
694 profileFd = null;
695 } catch (IOException e2) {
696 Slog.w(TAG, "Failure closing profile fd", e2);
697 }
698 }
699 }
700 public void stopProfiling() {
701 if (profiling) {
702 profiling = false;
703 Debug.stopMethodTracing();
704 if (profileFd != null) {
705 try {
706 profileFd.close();
707 } catch (IOException e) {
708 }
709 }
710 profileFd = null;
711 profileFile = null;
712 }
713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
715
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400716 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700717 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700718 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800719 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 }
722
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400723 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800724 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 String what;
726 String who;
727 }
728
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400729 static final class DumpHeapData {
Christopher Ferris8d652f82017-04-11 16:29:18 -0700730 public boolean managed;
731 public boolean mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700732 public boolean runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700733 String path;
734 ParcelFileDescriptor fd;
735 }
736
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400737 static final class UpdateCompatibilityData {
738 String pkg;
739 CompatibilityInfo info;
740 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800741
Adam Skorydfc7fd72013-08-05 19:23:41 -0700742 static final class RequestAssistContextExtras {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800743 IBinder activityToken;
744 IBinder requestToken;
745 int requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700746 int sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -0700747 int flags;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800748 }
Anwar Ghuloum3a8ce1b2013-04-26 16:18:28 -0700749
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700750 private class ApplicationThread extends IApplicationThread.Stub {
Vasu Nori3c7131f2010-09-21 14:36:57 -0700751 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700752
Dianne Hackborna413dc02013-07-12 12:02:55 -0700753 private int mLastProcessState = -1;
754
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700755 private void updatePendingConfiguration(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -0700756 synchronized (mResourcesManager) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700757 if (mPendingConfiguration == null ||
758 mPendingConfiguration.isOtherSeqNewer(config)) {
759 mPendingConfiguration = config;
760 }
761 }
762 }
763
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800764 public final void scheduleSleeping(IBinder token, boolean sleeping) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700765 sendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800766 }
767
Wale Ogunwale60454db2015-01-23 16:05:07 -0800768 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 public final void scheduleRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800770 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Wale Ogunwale60454db2015-01-23 16:05:07 -0800771 int configChanges, boolean notResumed, Configuration config,
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700772 Configuration overrideConfig, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800773 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700774 configChanges, notResumed, config, overrideConfig, true, preserveWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 }
776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400778 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700779 boolean sync, int sendingUser, int processState) {
780 updateProcessState(processState, false);
Dianne Hackborne829fef2010-10-26 17:44:01 -0700781 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700782 sync, false, mAppThread.asBinder(), sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400784 r.compatInfo = compatInfo;
Jeff Brown9ef09972013-10-15 20:49:59 -0700785 sendMessage(H.RECEIVER, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 }
787
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400788 public final void scheduleCreateBackupAgent(ApplicationInfo app,
789 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700790 CreateBackupAgentData d = new CreateBackupAgentData();
791 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400792 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700793 d.backupMode = backupMode;
794
Jeff Brown9ef09972013-10-15 20:49:59 -0700795 sendMessage(H.CREATE_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700796 }
797
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400798 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
799 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700800 CreateBackupAgentData d = new CreateBackupAgentData();
801 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400802 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700803
Jeff Brown9ef09972013-10-15 20:49:59 -0700804 sendMessage(H.DESTROY_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700805 }
806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 public final void scheduleCreateService(IBinder token,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700808 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
809 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 CreateServiceData s = new CreateServiceData();
811 s.token = token;
812 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400813 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814
Jeff Brown9ef09972013-10-15 20:49:59 -0700815 sendMessage(H.CREATE_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 }
817
818 public final void scheduleBindService(IBinder token, Intent intent,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700819 boolean rebind, int processState) {
820 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 BindServiceData s = new BindServiceData();
822 s.token = token;
823 s.intent = intent;
824 s.rebind = rebind;
825
Amith Yamasani742a6712011-05-04 14:49:28 -0700826 if (DEBUG_SERVICE)
827 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
828 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
Jeff Brown9ef09972013-10-15 20:49:59 -0700829 sendMessage(H.BIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
831
832 public final void scheduleUnbindService(IBinder token, Intent intent) {
833 BindServiceData s = new BindServiceData();
834 s.token = token;
835 s.intent = intent;
836
Jeff Brown9ef09972013-10-15 20:49:59 -0700837 sendMessage(H.UNBIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 }
839
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700840 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
841 List<ServiceStartArgs> list = args.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700843 for (int i = 0; i < list.size(); i++) {
844 ServiceStartArgs ssa = list.get(i);
845 ServiceArgsData s = new ServiceArgsData();
846 s.token = token;
847 s.taskRemoved = ssa.taskRemoved;
848 s.startId = ssa.startId;
849 s.flags = ssa.flags;
850 s.args = ssa.args;
851
852 sendMessage(H.SERVICE_ARGS, s);
853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
855
856 public final void scheduleStopService(IBinder token) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700857 sendMessage(H.STOP_SERVICE, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 }
859
Jeff Hao1b012d32014-08-20 10:35:34 -0700860 public final void bindApplication(String processName, ApplicationInfo appInfo,
861 List<ProviderInfo> providers, ComponentName instrumentationName,
862 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
863 IInstrumentationWatcher instrumentationWatcher,
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800864 IUiAutomationConnection instrumentationUiConnection, int debugMode,
Pablo Ceballosa4d4e822015-10-05 10:27:52 -0700865 boolean enableBinderTracking, boolean trackAllocation,
866 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700867 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800868 String buildSerial, boolean autofillCompatibilityEnabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869
870 if (services != null) {
871 // Setup the service cache in the ServiceManager
872 ServiceManager.initServiceCache(services);
873 }
874
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800875 setCoreSettings(coreSettings);
876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 AppBindData data = new AppBindData();
878 data.processName = processName;
879 data.appInfo = appInfo;
880 data.providers = providers;
881 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 data.instrumentationArgs = instrumentationArgs;
883 data.instrumentationWatcher = instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800884 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 data.debugMode = debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400886 data.enableBinderTracking = enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700887 data.trackAllocation = trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -0700888 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700889 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400891 data.compatInfo = compatInfo;
Jeff Hao1b012d32014-08-20 10:35:34 -0700892 data.initProfilerInfo = profilerInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700893 data.buildSerial = buildSerial;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800894 data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;
Jeff Brown9ef09972013-10-15 20:49:59 -0700895 sendMessage(H.BIND_APPLICATION, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
897
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400898 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
899 SomeArgs args = SomeArgs.obtain();
900 args.arg1 = entryPoint;
901 args.arg2 = entryPointArgs;
902 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
903 }
904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 public final void scheduleExit() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700906 sendMessage(H.EXIT_APPLICATION, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
908
Christopher Tate5e1ab332009-09-01 20:32:49 -0700909 public final void scheduleSuicide() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700910 sendMessage(H.SUICIDE, null);
Christopher Tate5e1ab332009-09-01 20:32:49 -0700911 }
912
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100913 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
914 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
915 }
916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 public void updateTimeZone() {
918 TimeZone.setDefault(null);
919 }
920
Robert Greenwalt03595d02010-11-02 14:08:23 -0700921 public void clearDnsCache() {
922 // a non-standard API to get this to libcore
923 InetAddress.clearDnsCache();
Paul Jensene401d172014-09-12 10:47:39 -0400924 // Allow libcore to perform the necessary actions as it sees fit upon a network
925 // configuration change.
926 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Robert Greenwalt03595d02010-11-02 14:08:23 -0700927 }
928
Jason Monk83520b92014-05-09 15:16:06 -0400929 public void setHttpProxy(String host, String port, String exclList, Uri pacFileUrl) {
Paul Jensen72db88e2015-03-10 10:54:12 -0400930 final ConnectivityManager cm = ConnectivityManager.from(getSystemContext());
931 final Network network = cm.getBoundNetworkForProcess();
Paul Jensene0bef712014-12-10 15:12:18 -0500932 if (network != null) {
Paul Jensen72db88e2015-03-10 10:54:12 -0400933 Proxy.setHttpProxySystemProperty(cm.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -0500934 } else {
935 Proxy.setHttpProxySystemProperty(host, port, exclList, pacFileUrl);
936 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700937 }
938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 public void processInBackground() {
940 mH.removeMessages(H.GC_WHEN_IDLE);
941 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
942 }
943
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700944 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700945 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700946 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700947 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700948 data.token = servicetoken;
949 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -0700950 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700951 } catch (IOException e) {
952 Slog.w(TAG, "dumpService failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700953 } finally {
954 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 }
956 }
957
958 // This function exists to make sure all receiver dispatching is
959 // correctly ordered, since these are one-way calls and the binder driver
960 // applies transaction ordering per object for such calls.
961 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700962 int resultCode, String dataStr, Bundle extras, boolean ordered,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700963 boolean sticky, int sendingUser, int processState) throws RemoteException {
964 updateProcessState(processState, false);
Dianne Hackborn20e80982012-08-31 19:00:44 -0700965 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
966 sticky, sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 }
Bob Leee5408332009-09-04 18:31:17 -0700968
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800969 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 public void scheduleLowMemory() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700971 sendMessage(H.LOW_MEMORY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
973
Wale Ogunwale60454db2015-01-23 16:05:07 -0800974 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -0700975 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
976 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800977 }
978
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700979 @Override
Christopher Ferris8d652f82017-04-11 16:29:18 -0700980 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
981 ParcelFileDescriptor fd) {
Andy McFadden824c5102010-07-09 16:26:57 -0700982 DumpHeapData dhd = new DumpHeapData();
Christopher Ferris8d652f82017-04-11 16:29:18 -0700983 dhd.managed = managed;
984 dhd.mallocInfo = mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700985 dhd.runGc = runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700986 dhd.path = path;
987 dhd.fd = fd;
Christopher Ferris8d652f82017-04-11 16:29:18 -0700988 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
Andy McFadden824c5102010-07-09 16:26:57 -0700989 }
990
Leonard Mosescuf3409ce2016-10-06 17:32:05 -0700991 public void attachAgent(String agent) {
992 sendMessage(H.ATTACH_AGENT, agent);
993 }
994
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700995 public void setSchedulingGroup(int group) {
996 // Note: do this immediately, since going into the foreground
997 // should happen regardless of what pending work we have to do
998 // and the activity manager will wait for us to report back that
999 // we are done before sending us to the background.
1000 try {
1001 Process.setProcessGroup(Process.myPid(), group);
1002 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001003 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001004 }
1005 }
Bob Leee5408332009-09-04 18:31:17 -07001006
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001007 public void dispatchPackageBroadcast(int cmd, String[] packages) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001008 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001009 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001010
1011 public void scheduleCrash(String msg) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001012 sendMessage(H.SCHEDULE_CRASH, msg);
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001013 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07001014
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001015 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
Dianne Hackborn30d71892010-12-11 10:37:55 -08001016 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001017 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001018 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001019 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001020 data.token = activitytoken;
1021 data.prefix = prefix;
1022 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001023 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001024 } catch (IOException e) {
1025 Slog.w(TAG, "dumpActivity failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001026 } finally {
1027 IoUtils.closeQuietly(pfd);
Dianne Hackborn625ac272010-09-17 18:29:22 -07001028 }
1029 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07001030
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001031 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
Marco Nelissen18cb2872011-11-15 11:19:53 -08001032 String[] args) {
1033 DumpComponentInfo data = new DumpComponentInfo();
1034 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001035 data.fd = pfd.dup();
Marco Nelissen18cb2872011-11-15 11:19:53 -08001036 data.token = providertoken;
1037 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001038 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001039 } catch (IOException e) {
1040 Slog.w(TAG, "dumpProvider failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001041 } finally {
1042 IoUtils.closeQuietly(pfd);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001043 }
1044 }
1045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001047 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001048 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1049 boolean dumpUnreachable, String[] args) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001050 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
Dianne Hackborn8c841092013-06-24 13:46:13 -07001051 PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001052 try {
Colin Crossc4fb5f92016-02-02 16:51:15 -08001053 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001054 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -07001055 pw.flush();
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001056 IoUtils.closeQuietly(pfd);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001057 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001058 }
1059
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001060 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001061 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 long nativeMax = Debug.getNativeHeapSize() / 1024;
1063 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1064 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 Runtime runtime = Runtime.getRuntime();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001067 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 long dalvikMax = runtime.totalMemory() / 1024;
1069 long dalvikFree = runtime.freeMemory() / 1024;
1070 long dalvikAllocated = dalvikMax - dalvikFree;
Richard Uhler2c036192016-09-14 09:48:31 +01001071
1072 Class[] classesToCount = new Class[] {
1073 ContextImpl.class,
1074 Activity.class,
1075 WebView.class,
1076 OpenSSLSocketImpl.class
1077 };
1078 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1079 long appContextInstanceCount = instanceCounts[0];
1080 long activityInstanceCount = instanceCounts[1];
1081 long webviewInstanceCount = instanceCounts[2];
1082 long openSslSocketCount = instanceCounts[3];
1083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -07001085 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 int globalAssetCount = AssetManager.getGlobalAssetCount();
1087 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1088 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1089 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1090 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001091 long parcelSize = Parcel.getGlobalAllocSize();
1092 long parcelCount = Parcel.getGlobalAllocCount();
Vasu Noric3849202010-03-09 10:47:25 -08001093 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -07001094
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07001095 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1096 Process.myPid(),
Dianne Hackborne77187d2013-10-25 16:32:41 -07001097 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1098 nativeMax, nativeAllocated, nativeFree,
1099 dalvikMax, dalvikAllocated, dalvikFree);
1100
Dianne Hackbornb437e092011-08-05 17:50:29 -07001101 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 // NOTE: if you change anything significant below, also consider changing
1103 // ACTIVITY_THREAD_CHECKIN_VERSION.
Anwar Ghuloum3c615062013-05-13 14:18:02 -07001104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 // Object counts
1106 pw.print(viewInstanceCount); pw.print(',');
1107 pw.print(viewRootInstanceCount); pw.print(',');
1108 pw.print(appContextInstanceCount); pw.print(',');
1109 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 pw.print(globalAssetCount); pw.print(',');
1112 pw.print(globalAssetManagerCount); pw.print(',');
1113 pw.print(binderLocalObjectCount); pw.print(',');
1114 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 pw.print(binderDeathObjectCount); pw.print(',');
1117 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 // SQL
Vasu Noric3849202010-03-09 10:47:25 -08001120 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -08001121 pw.print(stats.memoryUsed / 1024); pw.print(',');
1122 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -07001123 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001124 for (int i = 0; i < stats.dbStats.size(); i++) {
1125 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -07001126 pw.print(','); pw.print(dbStats.dbName);
1127 pw.print(','); pw.print(dbStats.pageSize);
1128 pw.print(','); pw.print(dbStats.dbSize);
1129 pw.print(','); pw.print(dbStats.lookaside);
1130 pw.print(','); pw.print(dbStats.cache);
1131 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -08001132 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07001133 pw.println();
Bob Leee5408332009-09-04 18:31:17 -07001134
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001135 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
Bob Leee5408332009-09-04 18:31:17 -07001137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 pw.println(" ");
1139 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001140 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 viewRootInstanceCount);
1142
1143 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1144 "Activities:", activityInstanceCount);
1145
1146 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1147 "AssetManagers:", globalAssetManagerCount);
1148
1149 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1150 "Proxy Binders:", binderProxyObjectCount);
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001151 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1152 "Parcel count:", parcelCount);
1153 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1154 "OpenSSL Sockets:", openSslSocketCount);
Richard Uhler2c036192016-09-14 09:48:31 +01001155 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
Bob Leee5408332009-09-04 18:31:17 -07001156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 // SQLite mem info
1158 pw.println(" ");
1159 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001160 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1161 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1162 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001163 pw.println(" ");
1164 int N = stats.dbStats.size();
1165 if (N > 0) {
1166 pw.println(" DATABASES");
Kweku Adams983829f2017-12-06 14:53:50 -08001167 printRow(pw, DB_INFO_FORMAT, "pgsz", "dbsz", "Lookaside(b)", "cache",
Vasu Nori3c7131f2010-09-21 14:36:57 -07001168 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001169 for (int i = 0; i < N; i++) {
1170 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001171 printRow(pw, DB_INFO_FORMAT,
1172 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1173 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1174 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1175 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001176 }
1177 }
Bob Leee5408332009-09-04 18:31:17 -07001178
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001179 // Asset details.
1180 String assetAlloc = AssetManager.getAssetAllocations();
1181 if (assetAlloc != null) {
1182 pw.println(" ");
1183 pw.println(" Asset Allocations");
1184 pw.print(assetAlloc);
1185 }
Colin Crossc4fb5f92016-02-02 16:51:15 -08001186
1187 // Unreachable native memory
1188 if (dumpUnreachable) {
1189 boolean showContents = ((mBoundApplication != null)
1190 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1191 || android.os.Build.IS_DEBUGGABLE;
1192 pw.println(" ");
1193 pw.println(" Unreachable memory");
1194 pw.print(Debug.getUnreachableMemory(100, showContents));
1195 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001196 }
1197
1198 @Override
Kweku Adams983829f2017-12-06 14:53:50 -08001199 public void dumpMemInfoProto(ParcelFileDescriptor pfd, Debug.MemoryInfo mem,
1200 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1201 boolean dumpUnreachable, String[] args) {
1202 ProtoOutputStream proto = new ProtoOutputStream(pfd.getFileDescriptor());
1203 try {
1204 dumpMemInfo(proto, mem, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1205 } finally {
1206 proto.flush();
1207 IoUtils.closeQuietly(pfd);
1208 }
1209 }
1210
1211 private void dumpMemInfo(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
1212 boolean dumpFullInfo, boolean dumpDalvik,
1213 boolean dumpSummaryOnly, boolean dumpUnreachable) {
1214 long nativeMax = Debug.getNativeHeapSize() / 1024;
1215 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1216 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1217
1218 Runtime runtime = Runtime.getRuntime();
1219 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1220 long dalvikMax = runtime.totalMemory() / 1024;
1221 long dalvikFree = runtime.freeMemory() / 1024;
1222 long dalvikAllocated = dalvikMax - dalvikFree;
1223
1224 Class[] classesToCount = new Class[] {
1225 ContextImpl.class,
1226 Activity.class,
1227 WebView.class,
1228 OpenSSLSocketImpl.class
1229 };
1230 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1231 long appContextInstanceCount = instanceCounts[0];
1232 long activityInstanceCount = instanceCounts[1];
1233 long webviewInstanceCount = instanceCounts[2];
1234 long openSslSocketCount = instanceCounts[3];
1235
1236 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1237 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1238 int globalAssetCount = AssetManager.getGlobalAssetCount();
1239 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1240 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1241 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1242 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1243 long parcelSize = Parcel.getGlobalAllocSize();
1244 long parcelCount = Parcel.getGlobalAllocCount();
1245 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1246
1247 final long mToken = proto.start(MemInfoProto.AppData.PROCESS_MEMORY);
1248 proto.write(MemInfoProto.ProcessMemory.PID, Process.myPid());
1249 proto.write(MemInfoProto.ProcessMemory.PROCESS_NAME,
1250 (mBoundApplication != null) ? mBoundApplication.processName : "unknown");
1251 dumpMemInfoTable(proto, memInfo, dumpDalvik, dumpSummaryOnly,
1252 nativeMax, nativeAllocated, nativeFree,
1253 dalvikMax, dalvikAllocated, dalvikFree);
1254 proto.end(mToken);
1255
1256 final long oToken = proto.start(MemInfoProto.AppData.OBJECTS);
1257 proto.write(MemInfoProto.AppData.ObjectStats.VIEW_INSTANCE_COUNT, viewInstanceCount);
1258 proto.write(MemInfoProto.AppData.ObjectStats.VIEW_ROOT_INSTANCE_COUNT,
1259 viewRootInstanceCount);
1260 proto.write(MemInfoProto.AppData.ObjectStats.APP_CONTEXT_INSTANCE_COUNT,
1261 appContextInstanceCount);
1262 proto.write(MemInfoProto.AppData.ObjectStats.ACTIVITY_INSTANCE_COUNT,
1263 activityInstanceCount);
1264 proto.write(MemInfoProto.AppData.ObjectStats.GLOBAL_ASSET_COUNT, globalAssetCount);
1265 proto.write(MemInfoProto.AppData.ObjectStats.GLOBAL_ASSET_MANAGER_COUNT,
1266 globalAssetManagerCount);
1267 proto.write(MemInfoProto.AppData.ObjectStats.LOCAL_BINDER_OBJECT_COUNT,
1268 binderLocalObjectCount);
1269 proto.write(MemInfoProto.AppData.ObjectStats.PROXY_BINDER_OBJECT_COUNT,
1270 binderProxyObjectCount);
1271 proto.write(MemInfoProto.AppData.ObjectStats.PARCEL_MEMORY_KB, parcelSize / 1024);
1272 proto.write(MemInfoProto.AppData.ObjectStats.PARCEL_COUNT, parcelCount);
1273 proto.write(MemInfoProto.AppData.ObjectStats.BINDER_OBJECT_DEATH_COUNT,
1274 binderDeathObjectCount);
1275 proto.write(MemInfoProto.AppData.ObjectStats.OPEN_SSL_SOCKET_COUNT, openSslSocketCount);
1276 proto.write(MemInfoProto.AppData.ObjectStats.WEBVIEW_INSTANCE_COUNT,
1277 webviewInstanceCount);
1278 proto.end(oToken);
1279
1280 // SQLite mem info
1281 final long sToken = proto.start(MemInfoProto.AppData.SQL);
1282 proto.write(MemInfoProto.AppData.SqlStats.MEMORY_USED_KB, stats.memoryUsed / 1024);
1283 proto.write(MemInfoProto.AppData.SqlStats.PAGECACHE_OVERFLOW_KB,
1284 stats.pageCacheOverflow / 1024);
1285 proto.write(MemInfoProto.AppData.SqlStats.MALLOC_SIZE_KB, stats.largestMemAlloc / 1024);
1286 int n = stats.dbStats.size();
1287 for (int i = 0; i < n; i++) {
1288 DbStats dbStats = stats.dbStats.get(i);
1289
1290 final long dToken = proto.start(MemInfoProto.AppData.SqlStats.DATABASES);
1291 proto.write(MemInfoProto.AppData.SqlStats.Database.NAME, dbStats.dbName);
1292 proto.write(MemInfoProto.AppData.SqlStats.Database.PAGE_SIZE, dbStats.pageSize);
1293 proto.write(MemInfoProto.AppData.SqlStats.Database.DB_SIZE, dbStats.dbSize);
1294 proto.write(MemInfoProto.AppData.SqlStats.Database.LOOKASIDE_B, dbStats.lookaside);
1295 proto.write(MemInfoProto.AppData.SqlStats.Database.CACHE, dbStats.cache);
1296 proto.end(dToken);
1297 }
1298 proto.end(sToken);
1299
1300 // Asset details.
1301 String assetAlloc = AssetManager.getAssetAllocations();
1302 if (assetAlloc != null) {
1303 proto.write(MemInfoProto.AppData.ASSET_ALLOCATIONS, assetAlloc);
1304 }
1305
1306 // Unreachable native memory
1307 if (dumpUnreachable) {
1308 int flags = mBoundApplication == null ? 0 : mBoundApplication.appInfo.flags;
1309 boolean showContents = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
1310 || android.os.Build.IS_DEBUGGABLE;
1311 proto.write(MemInfoProto.AppData.UNREACHABLE_MEMORY,
1312 Debug.getUnreachableMemory(100, showContents));
1313 }
1314 }
1315
1316 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001317 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
Chris Craikfc294242016-12-13 18:10:46 -08001318 nDumpGraphicsInfo(pfd.getFileDescriptor());
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001319 WindowManagerGlobal.getInstance().dumpGfxInfo(pfd.getFileDescriptor(), args);
1320 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
1322
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001323 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args) {
1324 PrintWriter pw = new FastPrintWriter(
1325 new FileOutputStream(pfd.getFileDescriptor()));
Jeff Brown6754ba22011-12-14 20:20:01 -08001326 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1327 SQLiteDebug.dump(printer, args);
1328 pw.flush();
1329 }
1330
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001331 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001332 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001333 if (mSystemThread) {
Felipe Leme29de4922016-06-07 16:14:07 -07001334 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1335 // be consumed. But it must duplicate the file descriptor first, since caller might
1336 // be closing it.
1337 final ParcelFileDescriptor dup;
1338 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001339 dup = pfd.dup();
Felipe Leme29de4922016-06-07 16:14:07 -07001340 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001341 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
Felipe Leme29de4922016-06-07 16:14:07 -07001342 return;
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001343 } finally {
1344 IoUtils.closeQuietly(pfd);
Felipe Leme29de4922016-06-07 16:14:07 -07001345 }
1346
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001347 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1348 @Override
1349 public void run() {
Felipe Lemec74972f2016-06-08 09:12:37 -07001350 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001351 dumpDatabaseInfo(dup, args);
Felipe Lemec74972f2016-06-08 09:12:37 -07001352 } finally {
1353 IoUtils.closeQuietly(dup);
1354 }
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001355 }
1356 });
1357 } else {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001358 dumpDatabaseInfo(pfd, args);
1359 IoUtils.closeQuietly(pfd);
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001360 }
1361 }
1362
1363 @Override
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001364 public void unstableProviderDied(IBinder provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001365 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001366 }
1367
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001368 @Override
Adam Skorydfc7fd72013-08-05 19:23:41 -07001369 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
Svet Ganovfd31f852017-04-26 15:54:27 -07001370 int requestType, int sessionId, int flags) {
Adam Skorydfc7fd72013-08-05 19:23:41 -07001371 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001372 cmd.activityToken = activityToken;
1373 cmd.requestToken = requestToken;
1374 cmd.requestType = requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -07001375 cmd.sessionId = sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -07001376 cmd.flags = flags;
Jeff Brown9ef09972013-10-15 20:49:59 -07001377 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001378 }
1379
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001380 public void setCoreSettings(Bundle coreSettings) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001381 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001382 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001383
1384 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1385 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1386 ucd.pkg = pkg;
1387 ucd.info = info;
Jeff Brown9ef09972013-10-15 20:49:59 -07001388 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001389 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001390
1391 public void scheduleTrimMemory(int level) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001392 sendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001393 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001394
Craig Mautner5eda9b32013-07-02 11:58:16 -07001395 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001396 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001397 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001398
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001399 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
Craig Mautnereb8abf72014-07-02 15:04:09 -07001400 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001401 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
Craig Mautnereb8abf72014-07-02 15:04:09 -07001402 }
1403
Dianne Hackborna413dc02013-07-12 12:02:55 -07001404 public void setProcessState(int state) {
1405 updateProcessState(state, true);
1406 }
1407
1408 public void updateProcessState(int processState, boolean fromIpc) {
1409 synchronized (this) {
1410 if (mLastProcessState != processState) {
1411 mLastProcessState = processState;
Mathieu Chartier1e370902013-07-18 10:58:01 -07001412 // Update Dalvik state based on ActivityManager.PROCESS_STATE_* constants.
1413 final int DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
1414 final int DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
1415 int dalvikProcessState = DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE;
1416 // TODO: Tune this since things like gmail sync are important background but not jank perceptible.
1417 if (processState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
1418 dalvikProcessState = DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE;
1419 }
1420 VMRuntime.getRuntime().updateProcessState(dalvikProcessState);
Dianne Hackborna413dc02013-07-12 12:02:55 -07001421 if (false) {
1422 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
1423 + (fromIpc ? " (from ipc": ""));
1424 }
1425 }
1426 }
1427 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001428
Sudheer Shanka84a48952017-03-08 18:19:01 -08001429 /**
1430 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1431 * the main thread that it needs to wait for the network rules to get updated before
1432 * launching an activity.
1433 */
1434 @Override
1435 public void setNetworkBlockSeq(long procStateSeq) {
1436 synchronized (mNetworkPolicyLock) {
1437 mNetworkBlockSeq = procStateSeq;
1438 }
1439 }
1440
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001441 @Override
1442 public void scheduleInstallProvider(ProviderInfo provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001443 sendMessage(H.INSTALL_PROVIDER, provider);
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001444 }
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001445
1446 @Override
Neil Fullerb7146fe2016-11-15 16:52:15 +00001447 public final void updateTimePrefs(int timeFormatPreference) {
1448 final Boolean timeFormatPreferenceBool;
1449 // For convenience we are using the Intent extra values.
1450 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1451 timeFormatPreferenceBool = Boolean.FALSE;
1452 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1453 timeFormatPreferenceBool = Boolean.TRUE;
1454 } else {
1455 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1456 // (or unknown).
1457 timeFormatPreferenceBool = null;
1458 }
1459 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001460 }
Craig Mautneree2e45a2014-06-27 12:10:03 -07001461
1462 @Override
Craig Mautner8746a472014-07-24 15:12:54 -07001463 public void scheduleEnterAnimationComplete(IBinder token) {
1464 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1465 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001466
1467 @Override
1468 public void notifyCleartextNetwork(byte[] firstPacket) {
1469 if (StrictMode.vmCleartextNetworkEnabled()) {
1470 StrictMode.onCleartextNetworkDetected(firstPacket);
1471 }
1472 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001473
1474 @Override
1475 public void startBinderTracking() {
1476 sendMessage(H.START_BINDER_TRACKING, null);
1477 }
1478
1479 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001480 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001481 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001482 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001483 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001484 } finally {
1485 IoUtils.closeQuietly(pfd);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001486 }
1487 }
Wale Ogunwale5f986092015-12-04 15:35:38 -08001488
1489 @Override
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001490 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1491 IVoiceInteractor voiceInteractor) throws RemoteException {
1492 SomeArgs args = SomeArgs.obtain();
1493 args.arg1 = token;
1494 args.arg2 = voiceInteractor;
1495 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1496 }
Chad Brubakerc72875b2016-04-27 16:35:11 -07001497
1498 @Override
1499 public void handleTrustStorageUpdate() {
1500 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1501 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001502
1503 @Override
1504 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1505 ActivityThread.this.scheduleTransaction(transaction);
1506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 }
1508
Andrii Kulian446e8242017-10-26 15:17:29 -07001509 @Override
1510 public void updatePendingConfiguration(Configuration config) {
1511 mAppThread.updatePendingConfiguration(config);
1512 }
1513
1514 @Override
1515 public void updateProcessState(int processState, boolean fromIpc) {
1516 mAppThread.updateProcessState(processState, fromIpc);
1517 }
1518
Andrii Kulian446e8242017-10-26 15:17:29 -07001519 class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 public static final int BIND_APPLICATION = 110;
1521 public static final int EXIT_APPLICATION = 111;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 public static final int RECEIVER = 113;
1523 public static final int CREATE_SERVICE = 114;
1524 public static final int SERVICE_ARGS = 115;
1525 public static final int STOP_SERVICE = 116;
Dianne Hackborn09233282014-04-30 11:33:59 -07001526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 public static final int CONFIGURATION_CHANGED = 118;
1528 public static final int CLEAN_UP_CONTEXT = 119;
1529 public static final int GC_WHEN_IDLE = 120;
1530 public static final int BIND_SERVICE = 121;
1531 public static final int UNBIND_SERVICE = 122;
1532 public static final int DUMP_SERVICE = 123;
1533 public static final int LOW_MEMORY = 124;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001535 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001536 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001537 public static final int DESTROY_BACKUP_AGENT = 129;
1538 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001539 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001540 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001541 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001542 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001543 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001544 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001545 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001546 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001547 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001548 public static final int TRIM_MEMORY = 140;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001549 public static final int DUMP_PROVIDER = 141;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001550 public static final int UNSTABLE_PROVIDER_DIED = 142;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001551 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001552 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001553 public static final int INSTALL_PROVIDER = 145;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001554 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
Craig Mautner8746a472014-07-24 15:12:54 -07001555 public static final int ENTER_ANIMATION_COMPLETE = 149;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001556 public static final int START_BINDER_TRACKING = 150;
1557 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001558 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001559 public static final int ATTACH_AGENT = 155;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001560 public static final int APPLICATION_INFO_CHANGED = 156;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001561 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
Andrii Kulian446e8242017-10-26 15:17:29 -07001562 public static final int EXECUTE_TRANSACTION = 159;
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001565 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 switch (code) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 case BIND_APPLICATION: return "BIND_APPLICATION";
1568 case EXIT_APPLICATION: return "EXIT_APPLICATION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 case RECEIVER: return "RECEIVER";
1570 case CREATE_SERVICE: return "CREATE_SERVICE";
1571 case SERVICE_ARGS: return "SERVICE_ARGS";
1572 case STOP_SERVICE: return "STOP_SERVICE";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1574 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1575 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1576 case BIND_SERVICE: return "BIND_SERVICE";
1577 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1578 case DUMP_SERVICE: return "DUMP_SERVICE";
1579 case LOW_MEMORY: return "LOW_MEMORY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001581 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001582 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1583 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001584 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001585 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001586 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001587 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001588 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001589 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001590 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001591 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001592 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001593 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001594 case TRIM_MEMORY: return "TRIM_MEMORY";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001595 case DUMP_PROVIDER: return "DUMP_PROVIDER";
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001596 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
Adam Skorydfc7fd72013-08-05 19:23:41 -07001597 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
Craig Mautner5eda9b32013-07-02 11:58:16 -07001598 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001599 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
Craig Mautnereb8abf72014-07-02 15:04:09 -07001600 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
Craig Mautner8746a472014-07-24 15:12:54 -07001601 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001602 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001603 case ATTACH_AGENT: return "ATTACH_AGENT";
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001604 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001605 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
Andrii Kulian446e8242017-10-26 15:17:29 -07001606 case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001609 return Integer.toString(code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
1611 public void handleMessage(Message msg) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001612 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 case RELAUNCH_ACTIVITY: {
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001615 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001616 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001617 handleRelaunchActivity(r);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001618 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 case BIND_APPLICATION:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001621 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 AppBindData data = (AppBindData)msg.obj;
1623 handleBindApplication(data);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001624 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 break;
1626 case EXIT_APPLICATION:
1627 if (mInitialApplication != null) {
1628 mInitialApplication.onTerminate();
1629 }
1630 Looper.myLooper().quit();
1631 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 case RECEIVER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001633 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 handleReceiver((ReceiverData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001635 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 break;
1637 case CREATE_SERVICE:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001638 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 handleCreateService((CreateServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001640 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 break;
1642 case BIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001643 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 handleBindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001645 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 break;
1647 case UNBIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001648 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 handleUnbindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001650 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 break;
1652 case SERVICE_ARGS:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001653 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceStart: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 handleServiceArgs((ServiceArgsData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001655 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 break;
1657 case STOP_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001658 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 handleStopService((IBinder)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001660 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 case CONFIGURATION_CHANGED:
Andrii Kulian446e8242017-10-26 15:17:29 -07001663 handleConfigurationChanged((Configuration) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 break;
1665 case CLEAN_UP_CONTEXT:
1666 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1667 cci.context.performFinalCleanup(cci.who, cci.what);
1668 break;
1669 case GC_WHEN_IDLE:
1670 scheduleGcIdler();
1671 break;
1672 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001673 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 break;
1675 case LOW_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001676 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 handleLowMemory();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001678 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001680 case PROFILER_CONTROL:
Jeff Hao1b012d32014-08-20 10:35:34 -07001681 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001682 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001683 case CREATE_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001684 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001685 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001686 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001687 break;
1688 case DESTROY_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001689 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001690 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001691 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001692 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001693 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001694 Process.killProcess(Process.myPid());
1695 break;
1696 case REMOVE_PROVIDER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001697 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001698 completeRemoveProvider((ProviderRefCount)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001699 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001700 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001701 case ENABLE_JIT:
1702 ensureJitEnabled();
1703 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001704 case DISPATCH_PACKAGE_BROADCAST:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001705 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001706 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001707 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001708 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001709 case SCHEDULE_CRASH:
1710 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001711 case DUMP_HEAP:
Christopher Ferris8d652f82017-04-11 16:29:18 -07001712 handleDumpHeap((DumpHeapData) msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001713 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001714 case DUMP_ACTIVITY:
1715 handleDumpActivity((DumpComponentInfo)msg.obj);
1716 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001717 case DUMP_PROVIDER:
1718 handleDumpProvider((DumpComponentInfo)msg.obj);
1719 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001720 case SLEEPING:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001721 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001722 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001723 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001724 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001725 case SET_CORE_SETTINGS:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001726 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001727 handleSetCoreSettings((Bundle) msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001728 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001729 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001730 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1731 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001732 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001733 case TRIM_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001734 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001735 handleTrimMemory(msg.arg1);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001736 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001737 break;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001738 case UNSTABLE_PROVIDER_DIED:
1739 handleUnstableProviderDied((IBinder)msg.obj, false);
1740 break;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001741 case REQUEST_ASSIST_CONTEXT_EXTRAS:
1742 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001743 break;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001744 case TRANSLUCENT_CONVERSION_COMPLETE:
1745 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
1746 break;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001747 case INSTALL_PROVIDER:
1748 handleInstallProvider((ProviderInfo) msg.obj);
1749 break;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001750 case ON_NEW_ACTIVITY_OPTIONS:
1751 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
1752 onNewActivityOptions(pair.first, pair.second);
Dake Gu7ef70b02014-07-08 18:37:12 -07001753 break;
Craig Mautner8746a472014-07-24 15:12:54 -07001754 case ENTER_ANIMATION_COMPLETE:
1755 handleEnterAnimationComplete((IBinder) msg.obj);
1756 break;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001757 case START_BINDER_TRACKING:
1758 handleStartBinderTracking();
1759 break;
1760 case STOP_BINDER_TRACKING_AND_DUMP:
1761 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
1762 break;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001763 case LOCAL_VOICE_INTERACTION_STARTED:
1764 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
1765 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
Amith Yamasani61019112017-01-10 15:05:00 -08001766 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001767 case ATTACH_AGENT: {
1768 Application app = getApplication();
1769 handleAttachAgent((String) msg.obj, app != null ? app.mLoadedApk : null);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001770 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001771 }
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001772 case APPLICATION_INFO_CHANGED:
1773 mUpdatingSystemConfig = true;
1774 try {
1775 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
1776 } finally {
1777 mUpdatingSystemConfig = false;
1778 }
1779 break;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001780 case RUN_ISOLATED_ENTRY_POINT:
1781 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
1782 (String[]) ((SomeArgs) msg.obj).arg2);
1783 break;
Andrii Kulian446e8242017-10-26 15:17:29 -07001784 case EXECUTE_TRANSACTION:
Andrii Kulian04470682018-01-10 15:32:31 -08001785 final ClientTransaction transaction = (ClientTransaction) msg.obj;
1786 mTransactionExecutor.execute(transaction);
1787 if (isSystem()) {
1788 // Client transactions inside system process are recycled on the client side
1789 // instead of ClientLifecycleManager to avoid being cleared before this
1790 // message is handled.
1791 transaction.recycle();
1792 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001793 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001795 Object obj = msg.obj;
1796 if (obj instanceof SomeArgs) {
1797 ((SomeArgs) obj).recycle();
1798 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001799 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
1801 }
1802
Romain Guy65b345f2011-07-27 18:51:50 -07001803 private class Idler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001804 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001806 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001807 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001808 if (mBoundApplication != null && mProfiler.profileFd != null
1809 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001810 stopProfiling = true;
1811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 if (a != null) {
1813 mNewActivities = null;
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001814 IActivityManager am = ActivityManager.getService();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001815 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001817 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 TAG, "Reporting idle of " + a +
1819 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001820 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 if (a.activity != null && !a.activity.mFinished) {
1822 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001823 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001824 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001826 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 }
1828 }
1829 prev = a;
1830 a = a.nextIdle;
1831 prev.nextIdle = null;
1832 } while (a != null);
1833 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001834 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001835 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001836 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001837 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 return false;
1839 }
1840 }
1841
1842 final class GcIdler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001843 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 public final boolean queueIdle() {
1845 doGcIfNeeded();
1846 return false;
1847 }
1848 }
1849
Romain Guy65b345f2011-07-27 18:51:50 -07001850 public static ActivityThread currentActivityThread() {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08001851 return sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853
Wale Ogunwale9a6ef1e2015-06-02 13:41:00 -07001854 public static boolean isSystem() {
1855 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
1856 }
1857
Svetoslavfbf0eca2015-05-01 16:52:41 -07001858 public static String currentOpPackageName() {
1859 ActivityThread am = currentActivityThread();
1860 return (am != null && am.getApplication() != null)
1861 ? am.getApplication().getOpPackageName() : null;
1862 }
1863
Romain Guy65b345f2011-07-27 18:51:50 -07001864 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001865 ActivityThread am = currentActivityThread();
1866 return (am != null && am.mBoundApplication != null)
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07001867 ? am.mBoundApplication.appInfo.packageName : null;
1868 }
1869
1870 public static String currentProcessName() {
1871 ActivityThread am = currentActivityThread();
1872 return (am != null && am.mBoundApplication != null)
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001873 ? am.mBoundApplication.processName : null;
1874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875
Romain Guy65b345f2011-07-27 18:51:50 -07001876 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001877 ActivityThread am = currentActivityThread();
1878 return am != null ? am.mInitialApplication : null;
1879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001881 public static IPackageManager getPackageManager() {
1882 if (sPackageManager != null) {
1883 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1884 return sPackageManager;
1885 }
1886 IBinder b = ServiceManager.getService("package");
1887 //Slog.v("PackageManager", "default service binder = " + b);
1888 sPackageManager = IPackageManager.Stub.asInterface(b);
1889 //Slog.v("PackageManager", "default service = " + sPackageManager);
1890 return sPackageManager;
1891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892
Romain Guy65b345f2011-07-27 18:51:50 -07001893 private Configuration mMainThreadConfig = new Configuration();
Amith Yamasani4f128e42016-05-10 11:44:12 -07001894
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001895 Configuration applyConfigCompatMainThread(int displayDensity, Configuration config,
1896 CompatibilityInfo compat) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001897 if (config == null) {
1898 return null;
1899 }
Craig Mautner48d0d182013-06-11 07:53:06 -07001900 if (!compat.supportsScreen()) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001901 mMainThreadConfig.setTo(config);
1902 config = mMainThreadConfig;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001903 compat.applyToConfiguration(displayDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001904 }
1905 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001908 /**
Todd Kennedy39bfee52016-02-24 10:28:21 -08001909 * Creates the top level resources for the given package. Will return an existing
1910 * Resources if one has already been created.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001911 */
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07001912 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
Adam Lesinski082614c2016-03-04 14:33:47 -08001913 String[] libDirs, int displayId, LoadedApk pkgInfo) {
1914 return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,
1915 displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader());
Todd Kennedy39bfee52016-02-24 10:28:21 -08001916 }
1917
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001918 final Handler getHandler() {
1919 return mH;
1920 }
1921
Todd Kennedy233a0b12018-01-29 20:30:24 +00001922 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1923 int flags) {
1924 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
Amith Yamasani98edc952012-09-25 14:09:27 -07001925 }
1926
Todd Kennedy233a0b12018-01-29 20:30:24 +00001927 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1928 int flags, int userId) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001929 final boolean differentUser = (UserHandle.myUserId() != userId);
Craig Mautner88c05892013-06-28 09:47:45 -07001930 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001931 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001932 if (differentUser) {
1933 // Caching not supported across users
1934 ref = null;
1935 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 ref = mPackages.get(packageName);
1937 } else {
1938 ref = mResourcePackages.get(packageName);
1939 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001940
Todd Kennedy233a0b12018-01-29 20:30:24 +00001941 LoadedApk packageInfo = ref != null ? ref.get() : null;
1942 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
1943 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1944 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
1945 if (packageInfo != null && (packageInfo.mResources == null
1946 || packageInfo.mResources.getAssets().isUpToDate())) {
1947 if (packageInfo.isSecurityViolation()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1949 throw new SecurityException(
1950 "Requesting code from " + packageName
1951 + " to be run in process "
1952 + mBoundApplication.processName
1953 + "/" + mBoundApplication.appInfo.uid);
1954 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001955 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
1957 }
1958
1959 ApplicationInfo ai = null;
1960 try {
1961 ai = getPackageManager().getApplicationInfo(packageName,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001962 PackageManager.GET_SHARED_LIBRARY_FILES
1963 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1964 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001966 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 }
1968
1969 if (ai != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001970 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 }
1972
1973 return null;
1974 }
1975
Todd Kennedy233a0b12018-01-29 20:30:24 +00001976 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001977 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1979 boolean securityViolation = includeCode && ai.uid != 0
1980 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001981 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
Amith Yamasani742a6712011-05-04 14:49:28 -07001982 : true);
Dianne Hackbornfee756f2014-07-16 17:31:10 -07001983 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1985 |Context.CONTEXT_IGNORE_SECURITY))
1986 == Context.CONTEXT_INCLUDE_CODE) {
1987 if (securityViolation) {
1988 String msg = "Requesting code from " + ai.packageName
1989 + " (with uid " + ai.uid + ")";
1990 if (mBoundApplication != null) {
1991 msg = msg + " to be run in process "
1992 + mBoundApplication.processName + " (with uid "
1993 + mBoundApplication.appInfo.uid + ")";
1994 }
1995 throw new SecurityException(msg);
1996 }
1997 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001998 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07001999 registerPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 }
2001
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002002 @Override
Todd Kennedy233a0b12018-01-29 20:30:24 +00002003 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002004 CompatibilityInfo compatInfo) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002005 return getPackageInfo(ai, compatInfo, null, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 }
2007
Todd Kennedy233a0b12018-01-29 20:30:24 +00002008 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
Craig Mautner88c05892013-06-28 09:47:45 -07002009 synchronized (mResourcesManager) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002010 WeakReference<LoadedApk> ref;
2011 if (includeCode) {
2012 ref = mPackages.get(packageName);
2013 } else {
2014 ref = mResourcePackages.get(packageName);
2015 }
2016 return ref != null ? ref.get() : null;
2017 }
2018 }
2019
Todd Kennedy233a0b12018-01-29 20:30:24 +00002020 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002021 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2022 boolean registerPackage) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002023 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
Craig Mautner88c05892013-06-28 09:47:45 -07002024 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002025 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002026 if (differentUser) {
2027 // Caching not supported across users
2028 ref = null;
2029 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 ref = mPackages.get(aInfo.packageName);
2031 } else {
2032 ref = mResourcePackages.get(aInfo.packageName);
2033 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002034
Todd Kennedy233a0b12018-01-29 20:30:24 +00002035 LoadedApk packageInfo = ref != null ? ref.get() : null;
2036 if (packageInfo == null || (packageInfo.mResources != null
2037 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002038 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 : "Loading resource-only package ") + aInfo.packageName
2040 + " (in " + (mBoundApplication != null
2041 ? mBoundApplication.processName : null)
2042 + ")");
Todd Kennedy233a0b12018-01-29 20:30:24 +00002043 packageInfo =
Jeff Browndefd4a62014-03-10 21:24:37 -07002044 new LoadedApk(this, aInfo, compatInfo, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 securityViolation, includeCode &&
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002046 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
Narayan Kamathcb383182014-10-29 17:56:42 +00002047
2048 if (mSystemThread && "android".equals(aInfo.packageName)) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002049 packageInfo.installSystemApplicationInfo(aInfo,
2050 getSystemContext().mPackageInfo.getClassLoader());
Narayan Kamathcb383182014-10-29 17:56:42 +00002051 }
2052
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002053 if (differentUser) {
2054 // Caching not supported across users
2055 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 mPackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002057 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 } else {
2059 mResourcePackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002060 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 }
2062 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002063 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
2065 }
2066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 ActivityThread() {
Craig Mautner88c05892013-06-28 09:47:45 -07002068 mResourcesManager = ResourcesManager.getInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 }
2070
2071 public ApplicationThread getApplicationThread()
2072 {
2073 return mAppThread;
2074 }
2075
2076 public Instrumentation getInstrumentation()
2077 {
2078 return mInstrumentation;
2079 }
2080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002082 return mProfiler != null && mProfiler.profileFile != null
2083 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085
2086 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002087 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089
2090 public Looper getLooper() {
2091 return mLooper;
2092 }
2093
Jeff Sharkey8439ac02017-12-12 17:26:23 -07002094 public Executor getExecutor() {
2095 return mExecutor;
2096 }
2097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 public Application getApplication() {
2099 return mInitialApplication;
2100 }
Bob Leee5408332009-09-04 18:31:17 -07002101
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002102 public String getProcessName() {
2103 return mBoundApplication.processName;
2104 }
Bob Leee5408332009-09-04 18:31:17 -07002105
Dianne Hackborn21556372010-02-04 16:34:40 -08002106 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 synchronized (this) {
2108 if (mSystemContext == null) {
Jeff Browndefd4a62014-03-10 21:24:37 -07002109 mSystemContext = ContextImpl.createSystemContext(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 }
Jeff Browndefd4a62014-03-10 21:24:37 -07002111 return mSystemContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114
Adam Lesinskia82b6262017-03-21 16:56:17 -07002115 public ContextImpl getSystemUiContext() {
2116 synchronized (this) {
2117 if (mSystemUiContext == null) {
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002118 mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
Adam Lesinskia82b6262017-03-21 16:56:17 -07002119 }
2120 return mSystemUiContext;
2121 }
2122 }
2123
Narayan Kamath29564cd2014-08-07 10:57:40 +01002124 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Mike Cleron432b7132009-09-24 15:28:29 -07002125 synchronized (this) {
Narayan Kamath29564cd2014-08-07 10:57:40 +01002126 getSystemContext().installSystemApplicationInfo(info, classLoader);
Adam Lesinskia82b6262017-03-21 16:56:17 -07002127 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002128
2129 // give ourselves a default profiler
2130 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07002131 }
2132 }
2133
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002134 void ensureJitEnabled() {
2135 if (!mJitEnabled) {
2136 mJitEnabled = true;
2137 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
2138 }
2139 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 void scheduleGcIdler() {
2142 if (!mGcIdlerScheduled) {
2143 mGcIdlerScheduled = true;
2144 Looper.myQueue().addIdleHandler(mGcIdler);
2145 }
2146 mH.removeMessages(H.GC_WHEN_IDLE);
2147 }
2148
2149 void unscheduleGcIdler() {
2150 if (mGcIdlerScheduled) {
2151 mGcIdlerScheduled = false;
2152 Looper.myQueue().removeIdleHandler(mGcIdler);
2153 }
2154 mH.removeMessages(H.GC_WHEN_IDLE);
2155 }
2156
2157 void doGcIfNeeded() {
2158 mGcIdlerScheduled = false;
2159 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002160 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 // + "m now=" + now);
2162 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002163 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 BinderInternal.forceGc("bg");
2165 }
2166 }
2167
Dianne Hackborne77187d2013-10-25 16:32:41 -07002168 private static final String HEAP_FULL_COLUMN
2169 = "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2170 private static final String HEAP_COLUMN
2171 = "%13s %8s %8s %8s %8s %8s %8s %8s";
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002172 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2173 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
2174 private static final String ONE_COUNT_COLUMN_HEADER = "%21s %8s";
Dianne Hackborne77187d2013-10-25 16:32:41 -07002175
2176 // Formatting for checkin service - update version if row format changes
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002177 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002178
2179 static void printRow(PrintWriter pw, String format, Object...objs) {
2180 pw.println(String.format(format, objs));
2181 }
2182
Bryce Leed946f862018-01-16 15:59:47 -08002183 @Override
2184 public void dump(PrintWriter pw, String prefix) {
2185 pw.println(prefix + "mActivities:");
2186
2187 for (ArrayMap.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
2188 pw.println(prefix + " [token:" + entry.getKey().hashCode() + " record:"
2189 + entry.getValue().toString() + "]");
2190 }
2191
2192 pw.println(prefix + "mRecentTokens:" + mRecentTokens);
2193 }
2194
Dianne Hackborne77187d2013-10-25 16:32:41 -07002195 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002196 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2197 int pid, String processName,
Dianne Hackborne77187d2013-10-25 16:32:41 -07002198 long nativeMax, long nativeAllocated, long nativeFree,
2199 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2200
2201 // For checkin, we print one long comma-separated list of values
2202 if (checkin) {
2203 // NOTE: if you change anything significant below, also consider changing
2204 // ACTIVITY_THREAD_CHECKIN_VERSION.
2205
2206 // Header
2207 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2208 pw.print(pid); pw.print(',');
2209 pw.print(processName); pw.print(',');
2210
2211 // Heap info - max
2212 pw.print(nativeMax); pw.print(',');
2213 pw.print(dalvikMax); pw.print(',');
2214 pw.print("N/A,");
2215 pw.print(nativeMax + dalvikMax); pw.print(',');
2216
2217 // Heap info - allocated
2218 pw.print(nativeAllocated); pw.print(',');
2219 pw.print(dalvikAllocated); pw.print(',');
2220 pw.print("N/A,");
2221 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2222
2223 // Heap info - free
2224 pw.print(nativeFree); pw.print(',');
2225 pw.print(dalvikFree); pw.print(',');
2226 pw.print("N/A,");
2227 pw.print(nativeFree + dalvikFree); pw.print(',');
2228
2229 // Heap info - proportional set size
2230 pw.print(memInfo.nativePss); pw.print(',');
2231 pw.print(memInfo.dalvikPss); pw.print(',');
2232 pw.print(memInfo.otherPss); pw.print(',');
2233 pw.print(memInfo.getTotalPss()); pw.print(',');
2234
2235 // Heap info - swappable set size
2236 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2237 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2238 pw.print(memInfo.otherSwappablePss); pw.print(',');
2239 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2240
2241 // Heap info - shared dirty
2242 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2243 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2244 pw.print(memInfo.otherSharedDirty); pw.print(',');
2245 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2246
2247 // Heap info - shared clean
2248 pw.print(memInfo.nativeSharedClean); pw.print(',');
2249 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2250 pw.print(memInfo.otherSharedClean); pw.print(',');
2251 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2252
2253 // Heap info - private Dirty
2254 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2255 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2256 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2257 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2258
2259 // Heap info - private Clean
2260 pw.print(memInfo.nativePrivateClean); pw.print(',');
2261 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2262 pw.print(memInfo.otherPrivateClean); pw.print(',');
2263 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2264
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002265 // Heap info - swapped out
2266 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2267 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2268 pw.print(memInfo.otherSwappedOut); pw.print(',');
2269 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2270
2271 // Heap info - swapped out pss
2272 if (memInfo.hasSwappedOutPss) {
2273 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2274 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2275 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2276 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2277 } else {
2278 pw.print("N/A,");
2279 pw.print("N/A,");
2280 pw.print("N/A,");
2281 pw.print("N/A,");
2282 }
2283
Dianne Hackborne77187d2013-10-25 16:32:41 -07002284 // Heap info - other areas
2285 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2286 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2287 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2288 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2289 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2290 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2291 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2292 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002293 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2294 if (memInfo.hasSwappedOutPss) {
2295 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2296 } else {
2297 pw.print("N/A,");
2298 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002299 }
2300 return;
2301 }
2302
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002303 if (!dumpSummaryOnly) {
2304 if (dumpFullInfo) {
2305 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002306 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2307 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002308 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
Martijn Coenene0764852016-01-07 17:04:22 -08002309 "Clean", "Clean", "Dirty",
2310 "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002311 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
2312 "------", "------", "------", "------", "------", "------");
2313 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2314 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2315 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002316 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002317 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002318 nativeMax, nativeAllocated, nativeFree);
2319 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2320 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2321 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002322 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002323 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002324 dalvikMax, dalvikAllocated, dalvikFree);
2325 } else {
2326 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002327 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2328 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002329 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
2330 "Clean", "Dirty", "Size", "Alloc", "Free");
2331 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
2332 "------", "------", "------", "------", "------");
2333 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2334 memInfo.nativePrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002335 memInfo.nativePrivateClean,
2336 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
2337 memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002338 nativeMax, nativeAllocated, nativeFree);
2339 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2340 memInfo.dalvikPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002341 memInfo.dalvikPrivateClean,
2342 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
2343 memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002344 dalvikMax, dalvikAllocated, dalvikFree);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002345 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002346
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002347 int otherPss = memInfo.otherPss;
2348 int otherSwappablePss = memInfo.otherSwappablePss;
2349 int otherSharedDirty = memInfo.otherSharedDirty;
2350 int otherPrivateDirty = memInfo.otherPrivateDirty;
2351 int otherSharedClean = memInfo.otherSharedClean;
2352 int otherPrivateClean = memInfo.otherPrivateClean;
2353 int otherSwappedOut = memInfo.otherSwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002354 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002355
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002356 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002357 final int myPss = memInfo.getOtherPss(i);
2358 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2359 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2360 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2361 final int mySharedClean = memInfo.getOtherSharedClean(i);
2362 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2363 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002364 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002365 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002366 || mySharedClean != 0 || myPrivateClean != 0
2367 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002368 if (dumpFullInfo) {
2369 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2370 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002371 mySharedClean, myPrivateClean,
2372 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2373 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002374 } else {
2375 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2376 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002377 myPrivateClean,
2378 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2379 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002380 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002381 otherPss -= myPss;
2382 otherSwappablePss -= mySwappablePss;
2383 otherSharedDirty -= mySharedDirty;
2384 otherPrivateDirty -= myPrivateDirty;
2385 otherSharedClean -= mySharedClean;
2386 otherPrivateClean -= myPrivateClean;
2387 otherSwappedOut -= mySwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002388 otherSwappedOutPss -= mySwappedOutPss;
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002389 }
2390 }
2391
2392 if (dumpFullInfo) {
2393 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
2394 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002395 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
2396 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002397 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
2398 memInfo.getTotalSwappablePss(),
2399 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2400 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
Thierry Strudel9b511602016-02-25 17:46:38 -08002401 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
2402 memInfo.getTotalSwappedOut(),
Martijn Coenene0764852016-01-07 17:04:22 -08002403 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
2404 nativeFree+dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002405 } else {
2406 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
Martijn Coenene0764852016-01-07 17:04:22 -08002407 otherPrivateDirty, otherPrivateClean,
2408 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002409 "", "", "");
2410 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
2411 memInfo.getTotalPrivateDirty(),
2412 memInfo.getTotalPrivateClean(),
Martijn Coenene0764852016-01-07 17:04:22 -08002413 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002414 memInfo.getTotalSwappedOut(),
2415 nativeMax+dalvikMax,
2416 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
2417 }
2418
2419 if (dumpDalvik) {
2420 pw.println(" ");
2421 pw.println(" Dalvik Details");
2422
2423 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
2424 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
2425 final int myPss = memInfo.getOtherPss(i);
2426 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2427 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2428 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2429 final int mySharedClean = memInfo.getOtherSharedClean(i);
2430 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2431 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002432 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002433 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002434 || mySharedClean != 0 || myPrivateClean != 0
2435 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002436 if (dumpFullInfo) {
2437 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2438 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002439 mySharedClean, myPrivateClean,
2440 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2441 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002442 } else {
2443 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2444 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002445 myPrivateClean,
2446 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2447 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002448 }
2449 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002450 }
2451 }
2452 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002453
2454 pw.println(" ");
2455 pw.println(" App Summary");
2456 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "Pss(KB)");
2457 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "------");
2458 printRow(pw, ONE_COUNT_COLUMN,
2459 "Java Heap:", memInfo.getSummaryJavaHeap());
2460 printRow(pw, ONE_COUNT_COLUMN,
2461 "Native Heap:", memInfo.getSummaryNativeHeap());
2462 printRow(pw, ONE_COUNT_COLUMN,
2463 "Code:", memInfo.getSummaryCode());
2464 printRow(pw, ONE_COUNT_COLUMN,
2465 "Stack:", memInfo.getSummaryStack());
2466 printRow(pw, ONE_COUNT_COLUMN,
2467 "Graphics:", memInfo.getSummaryGraphics());
2468 printRow(pw, ONE_COUNT_COLUMN,
2469 "Private Other:", memInfo.getSummaryPrivateOther());
2470 printRow(pw, ONE_COUNT_COLUMN,
2471 "System:", memInfo.getSummarySystem());
2472 pw.println(" ");
Martijn Coenene0764852016-01-07 17:04:22 -08002473 if (memInfo.hasSwappedOutPss) {
2474 printRow(pw, TWO_COUNT_COLUMNS,
2475 "TOTAL:", memInfo.getSummaryTotalPss(),
2476 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
2477 } else {
2478 printRow(pw, TWO_COUNT_COLUMNS,
2479 "TOTAL:", memInfo.getSummaryTotalPss(),
2480 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
2481 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002482 }
2483
Kweku Adams598e9a22017-11-02 17:12:20 -07002484 /**
2485 * Dump heap info to proto.
2486 *
2487 * @param hasSwappedOutPss determines whether to use dirtySwap or dirtySwapPss
2488 */
Kweku Adams983829f2017-12-06 14:53:50 -08002489 private static void dumpMemoryInfo(ProtoOutputStream proto, long fieldId, String name,
Kweku Adams598e9a22017-11-02 17:12:20 -07002490 int pss, int cleanPss, int sharedDirty, int privateDirty,
2491 int sharedClean, int privateClean,
2492 boolean hasSwappedOutPss, int dirtySwap, int dirtySwapPss) {
2493 final long token = proto.start(fieldId);
2494
Kweku Adams983829f2017-12-06 14:53:50 -08002495 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.NAME, name);
2496 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.TOTAL_PSS_KB, pss);
2497 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.CLEAN_PSS_KB, cleanPss);
2498 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.SHARED_DIRTY_KB, sharedDirty);
2499 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.PRIVATE_DIRTY_KB, privateDirty);
2500 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.SHARED_CLEAN_KB, sharedClean);
2501 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.PRIVATE_CLEAN_KB, privateClean);
Kweku Adams598e9a22017-11-02 17:12:20 -07002502 if (hasSwappedOutPss) {
Kweku Adams983829f2017-12-06 14:53:50 -08002503 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_PSS_KB, dirtySwapPss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002504 } else {
Kweku Adams983829f2017-12-06 14:53:50 -08002505 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_KB, dirtySwap);
Kweku Adams598e9a22017-11-02 17:12:20 -07002506 }
2507
2508 proto.end(token);
2509 }
2510
2511 /**
2512 * Dump mem info data to proto.
2513 */
2514 public static void dumpMemInfoTable(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
2515 boolean dumpDalvik, boolean dumpSummaryOnly,
2516 long nativeMax, long nativeAllocated, long nativeFree,
2517 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2518
2519 if (!dumpSummaryOnly) {
Kweku Adams983829f2017-12-06 14:53:50 -08002520 final long nhToken = proto.start(MemInfoProto.ProcessMemory.NATIVE_HEAP);
2521 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.HeapInfo.MEM_INFO, "Native Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002522 memInfo.nativePss, memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2523 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
2524 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss,
2525 memInfo.nativeSwappedOut, memInfo.nativeSwappedOutPss);
Kweku Adams983829f2017-12-06 14:53:50 -08002526 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax);
2527 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, nativeAllocated);
2528 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002529 proto.end(nhToken);
2530
Kweku Adams983829f2017-12-06 14:53:50 -08002531 final long dvToken = proto.start(MemInfoProto.ProcessMemory.DALVIK_HEAP);
2532 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.HeapInfo.MEM_INFO, "Dalvik Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002533 memInfo.dalvikPss, memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2534 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
2535 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss,
2536 memInfo.dalvikSwappedOut, memInfo.dalvikSwappedOutPss);
Kweku Adams983829f2017-12-06 14:53:50 -08002537 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, dalvikMax);
2538 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, dalvikAllocated);
2539 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002540 proto.end(dvToken);
2541
2542 int otherPss = memInfo.otherPss;
2543 int otherSwappablePss = memInfo.otherSwappablePss;
2544 int otherSharedDirty = memInfo.otherSharedDirty;
2545 int otherPrivateDirty = memInfo.otherPrivateDirty;
2546 int otherSharedClean = memInfo.otherSharedClean;
2547 int otherPrivateClean = memInfo.otherPrivateClean;
2548 int otherSwappedOut = memInfo.otherSwappedOut;
2549 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
2550
2551 for (int i = 0; i < Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2552 final int myPss = memInfo.getOtherPss(i);
2553 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2554 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2555 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2556 final int mySharedClean = memInfo.getOtherSharedClean(i);
2557 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2558 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2559 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2560 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2561 || mySharedClean != 0 || myPrivateClean != 0
2562 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Kweku Adams983829f2017-12-06 14:53:50 -08002563 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.OTHER_HEAPS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002564 Debug.MemoryInfo.getOtherLabel(i),
2565 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2566 mySharedClean, myPrivateClean,
2567 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2568
2569 otherPss -= myPss;
2570 otherSwappablePss -= mySwappablePss;
2571 otherSharedDirty -= mySharedDirty;
2572 otherPrivateDirty -= myPrivateDirty;
2573 otherSharedClean -= mySharedClean;
2574 otherPrivateClean -= myPrivateClean;
2575 otherSwappedOut -= mySwappedOut;
2576 otherSwappedOutPss -= mySwappedOutPss;
2577 }
2578 }
2579
Kweku Adams983829f2017-12-06 14:53:50 -08002580 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.UNKNOWN_HEAP, "Unknown",
Kweku Adams598e9a22017-11-02 17:12:20 -07002581 otherPss, otherSwappablePss,
2582 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
2583 memInfo.hasSwappedOutPss, otherSwappedOut, otherSwappedOutPss);
Kweku Adams983829f2017-12-06 14:53:50 -08002584 final long tToken = proto.start(MemInfoProto.ProcessMemory.TOTAL_HEAP);
2585 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.HeapInfo.MEM_INFO, "TOTAL",
Kweku Adams598e9a22017-11-02 17:12:20 -07002586 memInfo.getTotalPss(), memInfo.getTotalSwappablePss(),
2587 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2588 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
2589 memInfo.hasSwappedOutPss, memInfo.getTotalSwappedOut(),
2590 memInfo.getTotalSwappedOutPss());
Kweku Adams983829f2017-12-06 14:53:50 -08002591 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax + dalvikMax);
2592 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002593 nativeAllocated + dalvikAllocated);
Kweku Adams983829f2017-12-06 14:53:50 -08002594 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree + dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002595 proto.end(tToken);
2596
2597 if (dumpDalvik) {
2598 for (int i = Debug.MemoryInfo.NUM_OTHER_STATS;
2599 i < Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS;
2600 i++) {
2601 final int myPss = memInfo.getOtherPss(i);
2602 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2603 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2604 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2605 final int mySharedClean = memInfo.getOtherSharedClean(i);
2606 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2607 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2608 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2609 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2610 || mySharedClean != 0 || myPrivateClean != 0
2611 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Kweku Adams983829f2017-12-06 14:53:50 -08002612 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.DALVIK_DETAILS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002613 Debug.MemoryInfo.getOtherLabel(i),
2614 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2615 mySharedClean, myPrivateClean,
2616 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2617 }
2618 }
2619 }
2620 }
2621
Kweku Adams983829f2017-12-06 14:53:50 -08002622 final long asToken = proto.start(MemInfoProto.ProcessMemory.APP_SUMMARY);
2623 proto.write(MemInfoProto.ProcessMemory.AppSummary.JAVA_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002624 memInfo.getSummaryJavaHeap());
Kweku Adams983829f2017-12-06 14:53:50 -08002625 proto.write(MemInfoProto.ProcessMemory.AppSummary.NATIVE_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002626 memInfo.getSummaryNativeHeap());
Kweku Adams983829f2017-12-06 14:53:50 -08002627 proto.write(MemInfoProto.ProcessMemory.AppSummary.CODE_PSS_KB, memInfo.getSummaryCode());
2628 proto.write(MemInfoProto.ProcessMemory.AppSummary.STACK_PSS_KB, memInfo.getSummaryStack());
2629 proto.write(MemInfoProto.ProcessMemory.AppSummary.GRAPHICS_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002630 memInfo.getSummaryGraphics());
Kweku Adams983829f2017-12-06 14:53:50 -08002631 proto.write(MemInfoProto.ProcessMemory.AppSummary.PRIVATE_OTHER_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002632 memInfo.getSummaryPrivateOther());
Kweku Adams983829f2017-12-06 14:53:50 -08002633 proto.write(MemInfoProto.ProcessMemory.AppSummary.SYSTEM_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002634 memInfo.getSummarySystem());
2635 if (memInfo.hasSwappedOutPss) {
Kweku Adams983829f2017-12-06 14:53:50 -08002636 proto.write(MemInfoProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002637 memInfo.getSummaryTotalSwapPss());
2638 } else {
Kweku Adams983829f2017-12-06 14:53:50 -08002639 proto.write(MemInfoProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002640 memInfo.getSummaryTotalSwap());
2641 }
2642 proto.end(asToken);
2643 }
2644
Jeff Hamilton52d32032011-01-08 15:31:26 -06002645 public void registerOnActivityPausedListener(Activity activity,
2646 OnActivityPausedListener listener) {
2647 synchronized (mOnPauseListeners) {
2648 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2649 if (list == null) {
2650 list = new ArrayList<OnActivityPausedListener>();
2651 mOnPauseListeners.put(activity, list);
2652 }
2653 list.add(listener);
2654 }
2655 }
2656
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08002657 public void unregisterOnActivityPausedListener(Activity activity,
2658 OnActivityPausedListener listener) {
2659 synchronized (mOnPauseListeners) {
2660 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2661 if (list != null) {
2662 list.remove(listener);
2663 }
2664 }
2665 }
2666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 public final ActivityInfo resolveActivityInfo(Intent intent) {
2668 ActivityInfo aInfo = intent.resolveActivityInfo(
2669 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2670 if (aInfo == null) {
2671 // Throw an exception.
2672 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002673 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 }
2675 return aInfo;
2676 }
Bob Leee5408332009-09-04 18:31:17 -07002677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002680 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002681 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002683 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 r.intent = intent;
2685 r.state = state;
2686 r.parent = parent;
2687 r.embeddedID = id;
2688 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002689 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 if (localLOGV) {
2691 ComponentName compname = intent.getComponent();
2692 String name;
2693 if (compname != null) {
2694 name = compname.toShortString();
2695 } else {
2696 name = "(Intent " + intent + ").getComponent() returned null";
2697 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002698 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 + ", comp=" + name
2700 + ", token=" + token);
2701 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002702 // TODO(lifecycler): Can't switch to use #handleLaunchActivity() because it will try to
2703 // call #reportSizeConfigurations(), but the server might not know anything about the
2704 // activity if it was launched from LocalAcvitivyManager.
2705 return performLaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 }
2707
2708 public final Activity getActivity(IBinder token) {
2709 return mActivities.get(token).activity;
2710 }
2711
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002712 @Override
2713 public ActivityClientRecord getActivityClient(IBinder token) {
2714 return mActivities.get(token);
2715 }
2716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 public final void sendActivityResult(
2718 IBinder token, String id, int requestCode,
2719 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002720 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07002721 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2723 list.add(new ResultInfo(id, requestCode, resultCode, data));
Andrii Kulian9c5ea9c2017-12-07 09:31:01 -08002724 final ClientTransaction clientTransaction = ClientTransaction.obtain(mAppThread, token);
2725 clientTransaction.addCallback(ActivityResultItem.obtain(list));
Andrii Kulian446e8242017-10-26 15:17:29 -07002726 try {
2727 mAppThread.scheduleTransaction(clientTransaction);
2728 } catch (RemoteException e) {
2729 // Local scheduling
2730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 }
2732
Andrii Kulian446e8242017-10-26 15:17:29 -07002733 void sendMessage(int what, Object obj) {
Jeff Brown9ef09972013-10-15 20:49:59 -07002734 sendMessage(what, obj, 0, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 }
2736
Jeff Brown9ef09972013-10-15 20:49:59 -07002737 private void sendMessage(int what, Object obj, int arg1) {
2738 sendMessage(what, obj, arg1, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 }
2740
Jeff Brown9ef09972013-10-15 20:49:59 -07002741 private void sendMessage(int what, Object obj, int arg1, int arg2) {
2742 sendMessage(what, obj, arg1, arg2, false);
2743 }
2744
2745 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
2746 if (DEBUG_MESSAGES) Slog.v(
2747 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2748 + ": " + arg1 + " / " + obj);
2749 Message msg = Message.obtain();
2750 msg.what = what;
2751 msg.obj = obj;
2752 msg.arg1 = arg1;
2753 msg.arg2 = arg2;
2754 if (async) {
2755 msg.setAsynchronous(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 }
Jeff Brown9ef09972013-10-15 20:49:59 -07002757 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 }
2759
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07002760 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
2761 if (DEBUG_MESSAGES) Slog.v(
2762 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
2763 "seq= " + seq);
2764 Message msg = Message.obtain();
2765 msg.what = what;
2766 SomeArgs args = SomeArgs.obtain();
2767 args.arg1 = obj;
2768 args.argi1 = arg1;
2769 args.argi2 = arg2;
2770 args.argi3 = seq;
2771 msg.obj = args;
2772 mH.sendMessage(msg);
2773 }
2774
Dianne Hackborn21556372010-02-04 16:34:40 -08002775 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 String what) {
2777 ContextCleanupInfo cci = new ContextCleanupInfo();
2778 cci.context = context;
2779 cci.who = who;
2780 cci.what = what;
Jeff Brown9ef09972013-10-15 20:49:59 -07002781 sendMessage(H.CLEAN_UP_CONTEXT, cci);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 }
2783
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002784 /** Core implementation of activity launch. */
2785 private Activity performLaunchActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 ActivityInfo aInfo = r.activityInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00002787 if (r.packageInfo == null) {
2788 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 Context.CONTEXT_INCLUDE_CODE);
2790 }
Bob Leee5408332009-09-04 18:31:17 -07002791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 ComponentName component = r.intent.getComponent();
2793 if (component == null) {
2794 component = r.intent.resolveActivity(
2795 mInitialApplication.getPackageManager());
2796 r.intent.setComponent(component);
2797 }
2798
2799 if (r.activityInfo.targetActivity != null) {
2800 component = new ComponentName(r.activityInfo.packageName,
2801 r.activityInfo.targetActivity);
2802 }
2803
Adam Lesinski4e862812016-11-21 16:02:24 -08002804 ContextImpl appContext = createBaseContextForActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 Activity activity = null;
2806 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08002807 java.lang.ClassLoader cl = appContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04002808 activity = mInstrumentation.newActivity(
2809 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002810 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 r.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01002812 r.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 if (r.state != null) {
2814 r.state.setClassLoader(cl);
2815 }
2816 } catch (Exception e) {
2817 if (!mInstrumentation.onException(activity, e)) {
2818 throw new RuntimeException(
2819 "Unable to instantiate activity " + component
2820 + ": " + e.toString(), e);
2821 }
2822 }
2823
2824 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002825 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002826
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002827 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
2828 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 TAG, r + ": app=" + app
2830 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002831 + ", pkg=" + r.packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 + ", comp=" + r.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002833 + ", dir=" + r.packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834
2835 if (activity != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002837 Configuration config = new Configuration(mCompatConfiguration);
Andrii Kuliand0ad9382016-04-18 20:54:20 -07002838 if (r.overrideConfig != null) {
2839 config.updateFrom(r.overrideConfig);
2840 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002841 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002842 + r.activityInfo.name + " with config " + config);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07002843 Window window = null;
2844 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
2845 window = r.mPendingRemoveWindow;
2846 r.mPendingRemoveWindow = null;
2847 r.mPendingRemoveWindowManager = null;
2848 }
Adam Lesinski4e862812016-11-21 16:02:24 -08002849 appContext.setOuterContext(activity);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002850 activity.attach(appContext, this, getInstrumentation(), r.token,
2851 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Craig Mautner233ceee2014-05-09 17:05:11 -07002852 r.embeddedID, r.lastNonConfigurationInstances, config,
Andrii Kulian51c1b672017-04-07 18:39:32 -07002853 r.referrer, r.voiceInteractor, window, r.configCallback);
Bob Leee5408332009-09-04 18:31:17 -07002854
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002855 r.lastNonConfigurationInstances = null;
Sudheer Shanka84a48952017-03-08 18:19:01 -08002856 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 activity.mStartedActivity = false;
2858 int theme = r.activityInfo.getThemeResource();
2859 if (theme != 0) {
2860 activity.setTheme(theme);
2861 }
2862
2863 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07002864 if (r.isPersistable()) {
2865 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
2866 } else {
2867 mInstrumentation.callActivityOnCreate(activity, r.state);
2868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 if (!activity.mCalled) {
2870 throw new SuperNotCalledException(
2871 "Activity " + r.intent.getComponent().toShortString() +
2872 " did not call through to super.onCreate()");
2873 }
2874 r.activity = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002876 r.setState(ON_CREATE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877
2878 mActivities.put(r.token, r);
Bryce Leed946f862018-01-16 15:59:47 -08002879 mRecentTokens.push(r.token.hashCode());
2880
2881 if (mRecentTokens.size() > MAX_RECENT_TOKENS) {
2882 mRecentTokens.removeLast();
2883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884
2885 } catch (SuperNotCalledException e) {
2886 throw e;
2887
2888 } catch (Exception e) {
2889 if (!mInstrumentation.onException(activity, e)) {
2890 throw new RuntimeException(
2891 "Unable to start activity " + component
2892 + ": " + e.toString(), e);
2893 }
2894 }
2895
2896 return activity;
2897 }
2898
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002899 @Override
2900 public void handleStartActivity(ActivityClientRecord r,
2901 PendingTransactionActions pendingActions) {
2902 final Activity activity = r.activity;
2903 if (r.activity == null) {
2904 // TODO(lifecycler): What do we do in this case?
2905 return;
2906 }
2907 if (!r.stopped) {
2908 throw new IllegalStateException("Can't start activity that is not stopped.");
2909 }
2910 if (r.activity.mFinished) {
2911 // TODO(lifecycler): How can this happen?
2912 return;
2913 }
2914
2915 // Start
2916 activity.performStart();
2917 r.setState(ON_START);
2918
2919 if (pendingActions == null) {
2920 // No more work to do.
2921 return;
2922 }
2923
2924 // Restore instance state
2925 if (pendingActions.shouldRestoreInstanceState()) {
2926 if (r.isPersistable()) {
2927 if (r.state != null || r.persistentState != null) {
2928 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
2929 r.persistentState);
2930 }
2931 } else if (r.state != null) {
2932 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2933 }
2934 }
2935
2936 // Call postOnCreate()
2937 if (pendingActions.shouldCallOnPostCreate()) {
2938 activity.mCalled = false;
2939 if (r.isPersistable()) {
2940 mInstrumentation.callActivityOnPostCreate(activity, r.state,
2941 r.persistentState);
2942 } else {
2943 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2944 }
2945 if (!activity.mCalled) {
2946 throw new SuperNotCalledException(
2947 "Activity " + r.intent.getComponent().toShortString()
2948 + " did not call through to super.onPostCreate()");
2949 }
2950 }
2951 }
2952
Sudheer Shanka84a48952017-03-08 18:19:01 -08002953 /**
2954 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
2955 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
2956 * network rules to get updated.
2957 */
2958 private void checkAndBlockForNetworkAccess() {
2959 synchronized (mNetworkPolicyLock) {
2960 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
2961 try {
2962 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
2963 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
2964 } catch (RemoteException ignored) {}
2965 }
2966 }
2967 }
2968
Adam Lesinski4e862812016-11-21 16:02:24 -08002969 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
2970 final int displayId;
Craig Mautnere0a38842013-12-16 16:14:02 -08002971 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002972 displayId = ActivityManager.getService().getActivityDisplayId(r.token);
Craig Mautnere0a38842013-12-16 16:14:02 -08002973 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002974 throw e.rethrowFromSystemServer();
Craig Mautnere0a38842013-12-16 16:14:02 -08002975 }
Jeff Brownefd43bd2012-09-21 17:02:35 -07002976
Wale Ogunwale7c726682015-02-06 17:34:28 -08002977 ContextImpl appContext = ContextImpl.createActivityContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00002978 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
Wale Ogunwale7c726682015-02-06 17:34:28 -08002979
2980 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
Jeff Brownefd43bd2012-09-21 17:02:35 -07002981 // For debugging purposes, if the activity's package name contains the value of
2982 // the "debug.use-second-display" system property as a substring, then show
2983 // its content on a secondary display if there is one.
Jeff Brownefd43bd2012-09-21 17:02:35 -07002984 String pkgName = SystemProperties.get("debug.second-display.pkg");
2985 if (pkgName != null && !pkgName.isEmpty()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002986 && r.packageInfo.mPackageName.contains(pkgName)) {
Wale Ogunwale7c726682015-02-06 17:34:28 -08002987 for (int id : dm.getDisplayIds()) {
2988 if (id != Display.DEFAULT_DISPLAY) {
Wale Ogunwale26698512015-06-05 16:55:33 -07002989 Display display =
Bryce Lee609bf652017-02-09 16:50:13 -08002990 dm.getCompatibleDisplay(id, appContext.getResources());
Adam Lesinski4e862812016-11-21 16:02:24 -08002991 appContext = (ContextImpl) appContext.createDisplayContext(display);
Jeff Brownefd43bd2012-09-21 17:02:35 -07002992 break;
2993 }
2994 }
2995 }
Adam Lesinski4e862812016-11-21 16:02:24 -08002996 return appContext;
Jeff Brownefd43bd2012-09-21 17:02:35 -07002997 }
2998
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002999 /**
3000 * Extended implementation of activity launch. Used when server requests a launch or relaunch.
3001 */
Andrii Kulian446e8242017-10-26 15:17:29 -07003002 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003003 public Activity handleLaunchActivity(ActivityClientRecord r,
3004 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 // If we are getting ready to gc after going to the background, well
3006 // we are back active so skip it.
3007 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003008 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009
Jeff Hao1b012d32014-08-20 10:35:34 -07003010 if (r.profilerInfo != null) {
3011 mProfiler.setProfiler(r.profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003012 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003013 }
3014
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003015 // Make sure we are running with the most recent config.
3016 handleConfigurationChanged(null, null);
3017
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003018 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 TAG, "Handling launch of " + r);
Adam Powellcfbe9be2013-11-06 14:58:58 -08003020
Chet Haase0d1c27a2014-11-03 18:35:16 +00003021 // Initialize before creating the activity
Jesse Hallc37984f2017-05-23 16:55:08 -07003022 if (!ThreadedRenderer.sRendererDisabled) {
3023 GraphicsEnvironment.earlyInitEGL();
3024 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00003025 WindowManagerGlobal.initialize();
3026
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003027 final Activity a = performLaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028
3029 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003030 r.createdConfig = new Configuration(mConfiguration);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003031 reportSizeConfigurations(r);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003032 if (!r.activity.mFinished && pendingActions != null) {
3033 pendingActions.setOldState(r.state);
3034 pendingActions.setRestoreInstanceState(true);
3035 pendingActions.setCallOnPostCreate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 }
3037 } else {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003038 // 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 -08003039 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003040 ActivityManager.getService()
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003041 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
3042 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003044 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 }
3046 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003047
3048 return a;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 }
3050
Filip Gruszczynski23493322015-07-29 17:02:59 -07003051 private void reportSizeConfigurations(ActivityClientRecord r) {
3052 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
3053 if (configurations == null) {
3054 return;
3055 }
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003056 SparseIntArray horizontal = new SparseIntArray();
3057 SparseIntArray vertical = new SparseIntArray();
3058 SparseIntArray smallest = new SparseIntArray();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003059 for (int i = configurations.length - 1; i >= 0; i--) {
3060 Configuration config = configurations[i];
3061 if (config.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003062 vertical.put(config.screenHeightDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003063 }
3064 if (config.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003065 horizontal.put(config.screenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003066 }
3067 if (config.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003068 smallest.put(config.smallestScreenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003069 }
3070 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003071 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003072 ActivityManager.getService().reportSizeConfigurations(r.token,
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003073 horizontal.copyKeys(), vertical.copyKeys(), smallest.copyKeys());
Filip Gruszczynski23493322015-07-29 17:02:59 -07003074 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003075 throw ex.rethrowFromSystemServer();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003076 }
3077
3078 }
3079
Dianne Hackborn85d558c2014-11-04 10:31:54 -08003080 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 final int N = intents.size();
3082 for (int i=0; i<N; i++) {
Dianne Hackborna01a0fa2014-12-02 10:33:14 -08003083 ReferrerIntent intent = intents.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 intent.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003085 intent.prepareToEnterProcess();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003086 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
3088 }
3089 }
3090
Wale Ogunwale826c7062016-09-13 08:25:54 -07003091 void performNewIntents(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3092 final ActivityClientRecord r = mActivities.get(token);
3093 if (r == null) {
3094 return;
3095 }
3096
3097 final boolean resumed = !r.paused;
3098 if (resumed) {
3099 r.activity.mTemporaryPause = true;
3100 mInstrumentation.callActivityOnPause(r.activity);
3101 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003102 checkAndBlockForNetworkAccess();
Wale Ogunwale826c7062016-09-13 08:25:54 -07003103 deliverNewIntents(r, intents);
3104 if (resumed) {
Dake Gu67decfa2017-12-27 11:48:08 -08003105 r.activity.performResume(false);
Wale Ogunwale826c7062016-09-13 08:25:54 -07003106 r.activity.mTemporaryPause = false;
3107 }
3108
3109 if (r.paused && andPause) {
3110 // In this case the activity was in the paused state when we delivered the intent,
3111 // to guarantee onResume gets called after onNewIntent we temporarily resume the
3112 // activity and pause again as the caller wanted.
3113 performResumeActivity(token, false, "performNewIntents");
3114 performPauseActivityIfNeeded(r, "performNewIntents");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 }
3116 }
Bob Leee5408332009-09-04 18:31:17 -07003117
Andrii Kulian446e8242017-10-26 15:17:29 -07003118 @Override
3119 public void handleNewIntent(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3120 performNewIntents(token, intents, andPause);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 }
3122
Adam Skorydfc7fd72013-08-05 19:23:41 -07003123 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003124 // Filling for autofill has a few differences:
Felipe Leme1ca634a2016-11-28 17:21:21 -08003125 // - it does not need an AssistContent
3126 // - it does not call onProvideAssistData()
3127 // - it needs an IAutoFillCallback
Felipe Leme640f30a2017-03-06 15:44:06 -08003128 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
Felipe Leme1ca634a2016-11-28 17:21:21 -08003129
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003130 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani4f128e42016-05-10 11:44:12 -07003131 if (mLastSessionId != cmd.sessionId) {
3132 // Clear the existing structures
3133 mLastSessionId = cmd.sessionId;
3134 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
3135 AssistStructure structure = mLastAssistStructures.get(i).get();
3136 if (structure != null) {
3137 structure.clearSendChannel();
3138 }
3139 mLastAssistStructures.remove(i);
Dianne Hackborn782d4982015-07-08 17:36:37 -07003140 }
3141 }
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003142
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003143 Bundle data = new Bundle();
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003144 AssistStructure structure = null;
Felipe Leme640f30a2017-03-06 15:44:06 -08003145 AssistContent content = forAutofill ? null : new AssistContent();
Amith Yamasani858f98d2017-02-22 12:59:53 -08003146 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003147 ActivityClientRecord r = mActivities.get(cmd.activityToken);
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003148 Uri referrer = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003149 if (r != null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003150 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003151 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003152 r.activity.onProvideAssistData(data);
Felipe Leme6d553872016-12-08 17:13:25 -08003153 referrer = r.activity.onProvideReferrer();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003154 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003155 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill) {
Svet Ganovfd31f852017-04-26 15:54:27 -07003156 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
Adam Skory4aaed142015-04-22 11:29:31 -06003157 Intent activityIntent = r.activity.getIntent();
Felipe Leme6d553872016-12-08 17:13:25 -08003158 boolean notSecure = r.window == null ||
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003159 (r.window.getAttributes().flags
Felipe Leme6d553872016-12-08 17:13:25 -08003160 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3161 if (activityIntent != null && notSecure) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003162 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003163 Intent intent = new Intent(activityIntent);
3164 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3165 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3166 intent.removeUnsafeExtras();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003167 content.setDefaultIntent(intent);
3168 }
Adam Skory4aaed142015-04-22 11:29:31 -06003169 } else {
Felipe Leme640f30a2017-03-06 15:44:06 -08003170 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003171 content.setDefaultIntent(new Intent());
3172 }
Adam Skory4aaed142015-04-22 11:29:31 -06003173 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003174 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003175 r.activity.onProvideAssistContent(content);
3176 }
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07003177 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003178 }
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003179 if (structure == null) {
3180 structure = new AssistStructure();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003181 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08003182
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003183 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani858f98d2017-02-22 12:59:53 -08003184
3185 structure.setAcquisitionStartTime(startTime);
3186 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3187
Amith Yamasani4f128e42016-05-10 11:44:12 -07003188 mLastAssistStructures.add(new WeakReference<>(structure));
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003189 IActivityManager mgr = ActivityManager.getService();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003190 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003191 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003192 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003193 throw e.rethrowFromSystemServer();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003194 }
3195 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07003196
3197 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
3198 ActivityClientRecord r = mActivities.get(token);
3199 if (r != null) {
3200 r.activity.onTranslucentConversionComplete(drawComplete);
3201 }
3202 }
3203
Craig Mautnereb8abf72014-07-02 15:04:09 -07003204 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
3205 ActivityClientRecord r = mActivities.get(token);
3206 if (r != null) {
3207 r.activity.onNewActivityOptions(options);
3208 }
3209 }
3210
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003211 public void handleInstallProvider(ProviderInfo info) {
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003212 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3213 try {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003214 installContentProviders(mInitialApplication, Arrays.asList(info));
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003215 } finally {
3216 StrictMode.setThreadPolicy(oldPolicy);
3217 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003218 }
3219
Craig Mautner8746a472014-07-24 15:12:54 -07003220 private void handleEnterAnimationComplete(IBinder token) {
3221 ActivityClientRecord r = mActivities.get(token);
3222 if (r != null) {
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08003223 r.activity.dispatchEnterAnimationComplete();
Craig Mautner8746a472014-07-24 15:12:54 -07003224 }
3225 }
3226
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04003227 private void handleStartBinderTracking() {
3228 Binder.enableTracing();
3229 }
3230
3231 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
3232 try {
3233 Binder.disableTracing();
3234 Binder.getTransactionTracker().writeTracesToFile(fd);
3235 } finally {
3236 IoUtils.closeQuietly(fd);
3237 Binder.getTransactionTracker().clearTraces();
3238 }
3239 }
3240
Andrii Kulian446e8242017-10-26 15:17:29 -07003241 @Override
3242 public void handleMultiWindowModeChanged(IBinder token, boolean isInMultiWindowMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003243 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003244 final ActivityClientRecord r = mActivities.get(token);
3245 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003246 final Configuration newConfig = new Configuration(mConfiguration);
3247 if (overrideConfig != null) {
3248 newConfig.updateFrom(overrideConfig);
3249 }
3250 r.activity.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003251 }
3252 }
3253
Andrii Kulian446e8242017-10-26 15:17:29 -07003254 @Override
3255 public void handlePictureInPictureModeChanged(IBinder token, boolean isInPipMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003256 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003257 final ActivityClientRecord r = mActivities.get(token);
3258 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003259 final Configuration newConfig = new Configuration(mConfiguration);
3260 if (overrideConfig != null) {
3261 newConfig.updateFrom(overrideConfig);
3262 }
3263 r.activity.dispatchPictureInPictureModeChanged(isInPipMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003264 }
3265 }
3266
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003267 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
3268 final ActivityClientRecord r = mActivities.get(token);
3269 if (r != null) {
3270 r.voiceInteractor = interactor;
3271 r.activity.setVoiceInteractor(interactor);
3272 if (interactor == null) {
3273 r.activity.onLocalVoiceInteractionStopped();
3274 } else {
3275 r.activity.onLocalVoiceInteractionStarted();
3276 }
3277 }
3278 }
3279
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003280 private static boolean attemptAttachAgent(String agent, ClassLoader classLoader) {
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003281 try {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003282 VMDebug.attachAgent(agent, classLoader);
3283 return true;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003284 } catch (IOException e) {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003285 Slog.e(TAG, "Attaching agent with " + classLoader + " failed: " + agent);
3286 return false;
3287 }
3288 }
3289
3290 static void handleAttachAgent(String agent, LoadedApk loadedApk) {
3291 ClassLoader classLoader = loadedApk != null ? loadedApk.getClassLoader() : null;
3292 if (attemptAttachAgent(agent, classLoader)) {
3293 return;
3294 }
3295 if (classLoader != null) {
3296 attemptAttachAgent(agent, null);
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003297 }
3298 }
3299
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003300 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
3301
3302 /**
3303 * Return the Intent that's currently being handled by a
3304 * BroadcastReceiver on this thread, or null if none.
3305 * @hide
3306 */
3307 public static Intent getIntentBeingBroadcast() {
3308 return sCurrentBroadcastIntent.get();
3309 }
3310
Romain Guy65b345f2011-07-27 18:51:50 -07003311 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 // If we are getting ready to gc after going to the background, well
3313 // we are back active so skip it.
3314 unscheduleGcIdler();
3315
3316 String component = data.intent.getComponent().getClassName();
3317
Todd Kennedy233a0b12018-01-29 20:30:24 +00003318 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003319 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003321 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322
Adam Lesinski4e862812016-11-21 16:02:24 -08003323 Application app;
Romain Guy65b345f2011-07-27 18:51:50 -07003324 BroadcastReceiver receiver;
Adam Lesinski4e862812016-11-21 16:02:24 -08003325 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003327 app = packageInfo.makeApplication(false, mInstrumentation);
Adam Lesinski4e862812016-11-21 16:02:24 -08003328 context = (ContextImpl) app.getBaseContext();
3329 if (data.info.splitName != null) {
3330 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
3331 }
3332 java.lang.ClassLoader cl = context.getClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 data.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003334 data.intent.prepareToEnterProcess();
Dianne Hackborne829fef2010-10-26 17:44:01 -07003335 data.setExtrasClassLoader(cl);
Todd Kennedy233a0b12018-01-29 20:30:24 +00003336 receiver = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003337 .instantiateReceiver(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003339 if (DEBUG_BROADCAST) Slog.i(TAG,
3340 "Finishing failed broadcast to " + data.intent.getComponent());
3341 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 throw new RuntimeException(
3343 "Unable to instantiate receiver " + component
3344 + ": " + e.toString(), e);
3345 }
3346
3347 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003348 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 TAG, "Performing receive of " + data.intent
3350 + ": app=" + app
3351 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003352 + ", pkg=" + packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 + ", comp=" + data.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003354 + ", dir=" + packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003356 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07003357 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 receiver.onReceive(context.getReceiverRestrictedContext(),
3359 data.intent);
3360 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003361 if (DEBUG_BROADCAST) Slog.i(TAG,
3362 "Finishing failed broadcast to " + data.intent.getComponent());
3363 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 if (!mInstrumentation.onException(receiver, e)) {
3365 throw new RuntimeException(
3366 "Unable to start receiver " + component
3367 + ": " + e.toString(), e);
3368 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003369 } finally {
3370 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 }
3372
Dianne Hackborne829fef2010-10-26 17:44:01 -07003373 if (receiver.getPendingResult() != null) {
3374 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 }
3376 }
3377
Christopher Tate181fafa2009-05-14 11:12:14 -07003378 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07003379 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003380 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003381
Christopher Tate346acb12012-10-15 19:20:25 -07003382 // Sanity check the requested target package's uid against ours
3383 try {
3384 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
3385 data.appInfo.packageName, 0, UserHandle.myUserId());
3386 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
3387 Slog.w(TAG, "Asked to instantiate non-matching package "
3388 + data.appInfo.packageName);
3389 return;
3390 }
3391 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003392 throw e.rethrowFromSystemServer();
Christopher Tate346acb12012-10-15 19:20:25 -07003393 }
3394
Christopher Tate181fafa2009-05-14 11:12:14 -07003395 // no longer idle; we have backup work to do
3396 unscheduleGcIdler();
3397
3398 // instantiate the BackupAgent class named in the manifest
Todd Kennedy233a0b12018-01-29 20:30:24 +00003399 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3400 String packageName = packageInfo.mPackageName;
Christopher Tate346acb12012-10-15 19:20:25 -07003401 if (packageName == null) {
3402 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
3403 return;
3404 }
3405
Christopher Tate181fafa2009-05-14 11:12:14 -07003406 String classname = data.appInfo.backupAgentName;
Christopher Tate79ec80d2011-06-24 14:58:49 -07003407 // full backup operation but no app-supplied agent? use the default implementation
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003408 if (classname == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
3409 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07003410 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07003411 }
Christopher Tate4a627c72011-04-01 14:43:32 -07003412
Christopher Tate181fafa2009-05-14 11:12:14 -07003413 try {
Christopher Tated1475e02009-07-09 15:36:17 -07003414 IBinder binder = null;
Christopher Tate2e40d112014-07-15 12:37:38 -07003415 BackupAgent agent = mBackupAgents.get(packageName);
3416 if (agent != null) {
3417 // reusing the existing instance
3418 if (DEBUG_BACKUP) {
3419 Slog.v(TAG, "Reusing existing agent instance");
Christopher Tated1475e02009-07-09 15:36:17 -07003420 }
Christopher Tate2e40d112014-07-15 12:37:38 -07003421 binder = agent.onBind();
3422 } else {
3423 try {
3424 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
3425
Todd Kennedy233a0b12018-01-29 20:30:24 +00003426 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003427 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tate2e40d112014-07-15 12:37:38 -07003428
3429 // set up the agent's context
Todd Kennedy233a0b12018-01-29 20:30:24 +00003430 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Christopher Tate2e40d112014-07-15 12:37:38 -07003431 context.setOuterContext(agent);
3432 agent.attach(context);
3433
3434 agent.onCreate();
3435 binder = agent.onBind();
3436 mBackupAgents.put(packageName, agent);
3437 } catch (Exception e) {
3438 // If this is during restore, fail silently; otherwise go
3439 // ahead and let the user see the crash.
3440 Slog.e(TAG, "Agent threw during creation: " + e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003441 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
3442 && data.backupMode !=
3443 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
Christopher Tate2e40d112014-07-15 12:37:38 -07003444 throw e;
3445 }
3446 // falling through with 'binder' still null
3447 }
Christopher Tated1475e02009-07-09 15:36:17 -07003448 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003449
3450 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07003451 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003452 ActivityManager.getService().backupAgentCreated(packageName, binder);
Christopher Tate181fafa2009-05-14 11:12:14 -07003453 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003454 throw e.rethrowFromSystemServer();
Christopher Tate181fafa2009-05-14 11:12:14 -07003455 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003456 } catch (Exception e) {
3457 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07003458 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07003459 }
3460 }
3461
3462 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07003463 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003464 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07003465
Todd Kennedy233a0b12018-01-29 20:30:24 +00003466 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3467 String packageName = packageInfo.mPackageName;
Christopher Tate181fafa2009-05-14 11:12:14 -07003468 BackupAgent agent = mBackupAgents.get(packageName);
3469 if (agent != null) {
3470 try {
3471 agent.onDestroy();
3472 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003473 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07003474 e.printStackTrace();
3475 }
3476 mBackupAgents.remove(packageName);
3477 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003478 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003479 }
3480 }
3481
Romain Guy65b345f2011-07-27 18:51:50 -07003482 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 // If we are getting ready to gc after going to the background, well
3484 // we are back active so skip it.
3485 unscheduleGcIdler();
3486
Todd Kennedy233a0b12018-01-29 20:30:24 +00003487 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003488 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 Service service = null;
3490 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003491 java.lang.ClassLoader cl = packageInfo.getClassLoader();
3492 service = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003493 .instantiateService(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 } catch (Exception e) {
3495 if (!mInstrumentation.onException(service, e)) {
3496 throw new RuntimeException(
3497 "Unable to instantiate service " + data.info.name
3498 + ": " + e.toString(), e);
3499 }
3500 }
3501
3502 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003503 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504
Todd Kennedy233a0b12018-01-29 20:30:24 +00003505 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Jeff Browndefd4a62014-03-10 21:24:37 -07003506 context.setOuterContext(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507
Todd Kennedy233a0b12018-01-29 20:30:24 +00003508 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 service.attach(context, this, data.info.name, data.token, app,
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003510 ActivityManager.getService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 service.onCreate();
3512 mServices.put(data.token, service);
3513 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003514 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003515 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003517 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 }
3519 } catch (Exception e) {
3520 if (!mInstrumentation.onException(service, e)) {
3521 throw new RuntimeException(
3522 "Unable to create service " + data.info.name
3523 + ": " + e.toString(), e);
3524 }
3525 }
3526 }
3527
Romain Guy65b345f2011-07-27 18:51:50 -07003528 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07003530 if (DEBUG_SERVICE)
3531 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 if (s != null) {
3533 try {
3534 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003535 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 try {
3537 if (!data.rebind) {
3538 IBinder binder = s.onBind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003539 ActivityManager.getService().publishService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 data.token, data.intent, binder);
3541 } else {
3542 s.onRebind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003543 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003544 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003546 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003548 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 }
3550 } catch (Exception e) {
3551 if (!mInstrumentation.onException(s, e)) {
3552 throw new RuntimeException(
3553 "Unable to bind to service " + s
3554 + " with " + data.intent + ": " + e.toString(), e);
3555 }
3556 }
3557 }
3558 }
3559
Romain Guy65b345f2011-07-27 18:51:50 -07003560 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 Service s = mServices.get(data.token);
3562 if (s != null) {
3563 try {
3564 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003565 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 boolean doRebind = s.onUnbind(data.intent);
3567 try {
3568 if (doRebind) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003569 ActivityManager.getService().unbindFinished(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 data.token, data.intent, doRebind);
3571 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003572 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003573 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 }
3575 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003576 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 }
3578 } catch (Exception e) {
3579 if (!mInstrumentation.onException(s, e)) {
3580 throw new RuntimeException(
3581 "Unable to unbind to service " + s
3582 + " with " + data.intent + ": " + e.toString(), e);
3583 }
3584 }
3585 }
3586 }
3587
Dianne Hackborn625ac272010-09-17 18:29:22 -07003588 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003589 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3590 try {
3591 Service s = mServices.get(info.token);
3592 if (s != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003593 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3594 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003595 s.dump(info.fd.getFileDescriptor(), pw, info.args);
3596 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003598 } finally {
3599 IoUtils.closeQuietly(info.fd);
3600 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 }
3602 }
3603
Dianne Hackborn625ac272010-09-17 18:29:22 -07003604 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003605 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3606 try {
3607 ActivityClientRecord r = mActivities.get(info.token);
3608 if (r != null && r.activity != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003609 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3610 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003611 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
3612 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07003613 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003614 } finally {
3615 IoUtils.closeQuietly(info.fd);
3616 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07003617 }
3618 }
3619
Marco Nelissen18cb2872011-11-15 11:19:53 -08003620 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003621 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3622 try {
3623 ProviderClientRecord r = mLocalProviders.get(info.token);
3624 if (r != null && r.mLocalProvider != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003625 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3626 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003627 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
3628 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08003629 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003630 } finally {
3631 IoUtils.closeQuietly(info.fd);
3632 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08003633 }
3634 }
3635
Romain Guy65b345f2011-07-27 18:51:50 -07003636 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 Service s = mServices.get(data.token);
3638 if (s != null) {
3639 try {
3640 if (data.args != null) {
3641 data.args.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003642 data.args.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003644 int res;
3645 if (!data.taskRemoved) {
3646 res = s.onStartCommand(data.args, data.flags, data.startId);
3647 } else {
3648 s.onTaskRemoved(data.args);
3649 res = Service.START_TASK_REMOVED_COMPLETE;
3650 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003651
3652 QueuedWork.waitToFinish();
3653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003655 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003656 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003658 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003660 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 } catch (Exception e) {
3662 if (!mInstrumentation.onException(s, e)) {
3663 throw new RuntimeException(
3664 "Unable to start service " + s
3665 + " with " + data.args + ": " + e.toString(), e);
3666 }
3667 }
3668 }
3669 }
3670
Romain Guy65b345f2011-07-27 18:51:50 -07003671 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 Service s = mServices.remove(token);
3673 if (s != null) {
3674 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003675 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 s.onDestroy();
Amith Yamasani75928252017-05-22 15:10:47 -07003677 s.detachAndCleanUp();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003679 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08003681 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003683
3684 QueuedWork.waitToFinish();
3685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003687 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003688 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003690 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 }
3692 } catch (Exception e) {
3693 if (!mInstrumentation.onException(s, e)) {
3694 throw new RuntimeException(
3695 "Unable to stop service " + s
3696 + ": " + e.toString(), e);
3697 }
Craig Mautner66c4a822015-01-16 12:48:16 -08003698 Slog.i(TAG, "handleStopService: exception for " + token, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 }
Craig Mautner9776ad42015-01-15 14:38:39 -08003700 } else {
3701 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003703 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 }
3705
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003706 ActivityClientRecord performResumeActivity(IBinder token, boolean clearHide, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003707 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003708 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 + " finished=" + r.activity.mFinished);
3710 if (r != null && !r.activity.mFinished) {
3711 if (clearHide) {
3712 r.hideForNow = false;
3713 r.activity.mStartedActivity = false;
3714 }
3715 try {
Dianne Hackborn6bdd3a12015-08-05 15:01:28 -07003716 r.activity.onStateNotSaved();
Dianne Hackborn689586d2012-10-01 18:23:04 -07003717 r.activity.mFragments.noteStateNotSaved();
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003718 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 if (r.pendingIntents != null) {
3720 deliverNewIntents(r, r.pendingIntents);
3721 r.pendingIntents = null;
3722 }
3723 if (r.pendingResults != null) {
3724 deliverResults(r, r.pendingResults);
3725 r.pendingResults = null;
3726 }
Dake Gu67decfa2017-12-27 11:48:08 -08003727 r.activity.performResume(r.startsNotResumed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01003729 synchronized (mResourcesManager) {
3730 // If there is a pending local relaunch that was requested when the activity was
3731 // paused, it will put the activity into paused state when it finally happens.
3732 // Since the activity resumed before being relaunched, we don't want that to
3733 // happen, so we need to clear the request to relaunch paused.
3734 for (int i = mRelaunchingActivities.size() - 1; i >= 0; i--) {
3735 final ActivityClientRecord relaunching = mRelaunchingActivities.get(i);
3736 if (relaunching.token == r.token
3737 && relaunching.onlyLocalRequest && relaunching.startsNotResumed) {
3738 relaunching.startsNotResumed = false;
3739 }
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08003740 }
3741 }
3742
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003743 EventLog.writeEvent(LOG_AM_ON_RESUME_CALLED, UserHandle.myUserId(),
3744 r.activity.getComponentName().getClassName(), reason);
Bob Leee5408332009-09-04 18:31:17 -07003745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 r.state = null;
Craig Mautnera0026042014-04-23 11:45:37 -07003747 r.persistentState = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003748 r.setState(ON_RESUME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 } catch (Exception e) {
3750 if (!mInstrumentation.onException(r.activity, e)) {
3751 throw new RuntimeException(
3752 "Unable to resume activity "
3753 + r.intent.getComponent().toShortString()
3754 + ": " + e.toString(), e);
3755 }
3756 }
3757 }
3758 return r;
3759 }
3760
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003761 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
3762 if (r.mPreserveWindow && !force) {
3763 return;
3764 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003765 if (r.mPendingRemoveWindow != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003766 r.mPendingRemoveWindowManager.removeViewImmediate(
3767 r.mPendingRemoveWindow.getDecorView());
3768 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003769 if (wtoken != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07003770 WindowManagerGlobal.getInstance().closeAll(wtoken,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003771 r.activity.getClass().getName(), "Activity");
3772 }
3773 }
3774 r.mPendingRemoveWindow = null;
3775 r.mPendingRemoveWindowManager = null;
3776 }
3777
Andrii Kulian446e8242017-10-26 15:17:29 -07003778 @Override
3779 public void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward,
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003780 String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 // If we are getting ready to gc after going to the background, well
3782 // we are back active so skip it.
3783 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003784 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785
Adam Powellcfbe9be2013-11-06 14:58:58 -08003786 // TODO Push resumeArgs into the activity for consideration
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003787 final ActivityClientRecord r = performResumeActivity(token, clearHide, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788
3789 if (r != null) {
3790 final Activity a = r.activity;
3791
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003792 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 TAG, "Resume " + r + " started activity: " +
3794 a.mStartedActivity + ", hideForNow: " + r.hideForNow
3795 + ", finished: " + a.mFinished);
3796
3797 final int forwardBit = isForward ?
3798 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07003799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 // If the window hasn't yet been added to the window manager,
3801 // and this guy didn't finish itself or start another activity,
3802 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003803 boolean willBeVisible = !a.mStartedActivity;
3804 if (!willBeVisible) {
3805 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003806 willBeVisible = ActivityManager.getService().willActivityBeVisible(
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003807 a.getActivityToken());
3808 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003809 throw e.rethrowFromSystemServer();
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003810 }
3811 }
3812 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 r.window = r.activity.getWindow();
3814 View decor = r.window.getDecorView();
3815 decor.setVisibility(View.INVISIBLE);
3816 ViewManager wm = a.getWindowManager();
3817 WindowManager.LayoutParams l = r.window.getAttributes();
3818 a.mDecor = decor;
3819 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
3820 l.softInputMode |= forwardBit;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003821 if (r.mPreserveWindow) {
3822 a.mWindowAdded = true;
3823 r.mPreserveWindow = false;
Robert Carrb2594852016-04-25 16:21:13 -07003824 // Normally the ViewRoot sets up callbacks with the Activity
3825 // in addView->ViewRootImpl#setView. If we are instead reusing
3826 // the decor view we have to notify the view root that the
3827 // callbacks may have changed.
3828 ViewRootImpl impl = decor.getViewRootImpl();
Robert Carr311ecba2016-04-27 12:59:45 -07003829 if (impl != null) {
3830 impl.notifyChildRebuilt();
3831 }
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003832 }
Bryce Lee4b51b322017-04-07 10:27:19 -07003833 if (a.mVisibleFromClient) {
3834 if (!a.mWindowAdded) {
3835 a.mWindowAdded = true;
3836 wm.addView(decor, l);
3837 } else {
3838 // The activity will get a callback for this {@link LayoutParams} change
3839 // earlier. However, at that time the decor will not be set (this is set
3840 // in this method), so no action will be taken. This call ensures the
3841 // callback occurs with the decor set.
3842 a.onWindowAttributesChanged(l);
3843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 }
3845
3846 // If the window has already been added, but during resume
3847 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003848 // window visible.
3849 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003850 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 TAG, "Launch " + r + " mStartedActivity set");
3852 r.hideForNow = true;
3853 }
3854
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003855 // Get rid of anything left hanging around.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003856 cleanUpPendingRemoveWindows(r, false /* force */);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 // The window is now visible if it has been added, we are not
3859 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003860 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003861 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08003863 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003864 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Adam Lesinski082614c2016-03-04 14:33:47 -08003865 + r.activityInfo.name + " with newConfig " + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 r.newConfig = null;
3867 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003868 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 + isForward);
3870 WindowManager.LayoutParams l = r.window.getAttributes();
3871 if ((l.softInputMode
3872 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
3873 != forwardBit) {
3874 l.softInputMode = (l.softInputMode
3875 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
3876 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003877 if (r.activity.mVisibleFromClient) {
3878 ViewManager wm = a.getWindowManager();
3879 View decor = r.window.getDecorView();
3880 wm.updateViewLayout(decor, l);
3881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 }
Bryce Lee4b51b322017-04-07 10:27:19 -07003883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 r.activity.mVisibleFromServer = true;
3885 mNumVisibleActivities++;
3886 if (r.activity.mVisibleFromClient) {
3887 r.activity.makeVisible();
3888 }
3889 }
3890
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003891 if (!r.onlyLocalRequest) {
3892 r.nextIdle = mNewActivities;
3893 mNewActivities = r;
3894 if (localLOGV) Slog.v(
3895 TAG, "Scheduling idle handler for " + r);
3896 Looper.myQueue().addIdleHandler(new Idler());
3897 }
3898 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 } else {
3900 // If an exception was thrown when trying to resume, then
3901 // just end this activity.
3902 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003903 ActivityManager.getService()
Wale Ogunwaleba7881c2015-08-01 19:28:29 -07003904 .finishActivity(token, Activity.RESULT_CANCELED, null,
3905 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003907 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
3910 }
3911
3912 private int mThumbnailWidth = -1;
3913 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003914 private Bitmap mAvailThumbnailBitmap = null;
3915 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916
Romain Guy65b345f2011-07-27 18:51:50 -07003917 private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003918 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003920 if (thumbnail == null) {
3921 int w = mThumbnailWidth;
3922 int h;
3923 if (w < 0) {
3924 Resources res = r.activity.getResources();
Winson Chung6784f1c2014-05-22 11:22:41 -07003925 int wId = com.android.internal.R.dimen.thumbnail_width;
3926 int hId = com.android.internal.R.dimen.thumbnail_height;
Winson Chungfd086222014-05-13 15:49:42 -07003927 mThumbnailWidth = w = res.getDimensionPixelSize(wId);
3928 mThumbnailHeight = h = res.getDimensionPixelSize(hId);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003929 } else {
3930 h = mThumbnailHeight;
3931 }
3932
3933 // On platforms where we don't want thumbnails, set dims to (0,0)
3934 if ((w > 0) && (h > 0)) {
Dianne Hackborndde331c2012-08-03 14:01:57 -07003935 thumbnail = Bitmap.createBitmap(r.activity.getResources().getDisplayMetrics(),
3936 w, h, THUMBNAIL_FORMAT);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003937 thumbnail.eraseColor(0);
3938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 }
3940
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08003941 if (thumbnail != null) {
3942 Canvas cv = mThumbnailCanvas;
3943 if (cv == null) {
3944 mThumbnailCanvas = cv = new Canvas();
3945 }
Tim Murraye1e6c662015-04-07 13:24:14 -07003946
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08003947 cv.setBitmap(thumbnail);
3948 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
3949 mAvailThumbnailBitmap = thumbnail;
3950 thumbnail = null;
3951 }
Dianne Hackborn6311d0a2011-08-02 16:37:58 -07003952 cv.setBitmap(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07003954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 } catch (Exception e) {
3956 if (!mInstrumentation.onException(r.activity, e)) {
3957 throw new RuntimeException(
3958 "Unable to create thumbnail of "
3959 + r.intent.getComponent().toShortString()
3960 + ": " + e.toString(), e);
3961 }
3962 thumbnail = null;
3963 }
3964
3965 return thumbnail;
3966 }
3967
Andrii Kulian446e8242017-10-26 15:17:29 -07003968 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003969 public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
3970 int configChanges, boolean dontReport, PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003971 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 if (userLeaving) {
3974 performUserLeavingActivity(r);
3975 }
Bob Leee5408332009-09-04 18:31:17 -07003976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 r.activity.mConfigChangeFlags |= configChanges;
Andrii Kulian8ae79572018-01-26 15:36:06 -08003978 performPauseActivity(r, finished, "handlePauseActivity", pendingActions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07003980 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08003981 if (r.isPreHoneycomb()) {
3982 QueuedWork.waitToFinish();
3983 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07003984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 // Tell the activity manager we have paused.
Dianne Hackborna4e102e2014-09-04 22:52:27 -07003986 if (!dontReport) {
3987 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003988 ActivityManager.getService().activityPaused(token);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07003989 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003990 throw ex.rethrowFromSystemServer();
Dianne Hackborna4e102e2014-09-04 22:52:27 -07003991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003993 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 }
3995 }
3996
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003997 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 mInstrumentation.callActivityOnUserLeaving(r.activity);
3999 }
4000
Andrii Kulian8ae79572018-01-26 15:36:06 -08004001 final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
4002 PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004003 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004004 return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 }
4006
Andrii Kulian8ae79572018-01-26 15:36:06 -08004007 /**
4008 * Pause the activity.
4009 * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
4010 */
4011 private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
4012 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 if (r.paused) {
4014 if (r.activity.mFinished) {
4015 // If we are finishing, we won't call onResume() in certain cases.
4016 // So here we likewise don't want to call onPause() if the activity
4017 // isn't resumed.
4018 return null;
4019 }
4020 RuntimeException e = new RuntimeException(
4021 "Performing pause of activity that is not resumed: "
4022 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004023 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 if (finished) {
4026 r.activity.mFinished = true;
4027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028
Andrii Kulian8ae79572018-01-26 15:36:06 -08004029 // Pre-Honeycomb apps always save their state before pausing
4030 final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
4031 if (shouldSaveState) {
4032 callActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004034
4035 performPauseActivityIfNeeded(r, reason);
Jeff Hamilton52d32032011-01-08 15:31:26 -06004036
4037 // Notify any outstanding on paused listeners
4038 ArrayList<OnActivityPausedListener> listeners;
4039 synchronized (mOnPauseListeners) {
4040 listeners = mOnPauseListeners.remove(r.activity);
4041 }
4042 int size = (listeners != null ? listeners.size() : 0);
4043 for (int i = 0; i < size; i++) {
4044 listeners.get(i).onPaused(r.activity);
4045 }
4046
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004047 final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
4048 if (oldState != null) {
4049 // We need to keep around the original state, in case we need to be created again.
4050 // But we only do this for pre-Honeycomb apps, which always save their state when
4051 // pausing, so we can not have them save their state when restarting from a paused
4052 // state. For HC and later, we want to (and can) let the state be saved as the
4053 // normal part of stopping the activity.
4054 if (r.isPreHoneycomb()) {
4055 r.state = oldState;
4056 }
4057 }
4058
Andrii Kulian8ae79572018-01-26 15:36:06 -08004059 return shouldSaveState ? r.state : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 }
4061
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004062 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4063 if (r.paused) {
4064 // You are already paused silly...
4065 return;
4066 }
4067
4068 try {
4069 r.activity.mCalled = false;
4070 mInstrumentation.callActivityOnPause(r.activity);
4071 EventLog.writeEvent(LOG_AM_ON_PAUSE_CALLED, UserHandle.myUserId(),
4072 r.activity.getComponentName().getClassName(), reason);
4073 if (!r.activity.mCalled) {
4074 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4075 + " did not call through to super.onPause()");
4076 }
4077 } catch (SuperNotCalledException e) {
4078 throw e;
4079 } catch (Exception e) {
4080 if (!mInstrumentation.onException(r.activity, e)) {
4081 throw new RuntimeException("Unable to pause activity "
4082 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4083 }
4084 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004085 r.setState(ON_PAUSE);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004086 }
4087
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004088 final void performStopActivity(IBinder token, boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004089 ActivityClientRecord r = mActivities.get(token);
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004090 performStopActivityInner(r, null, false, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 }
4092
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004093 private static final class ProviderRefCount {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004094 public final ContentProviderHolder holder;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004095 public final ProviderClientRecord client;
4096 public int stableCount;
4097 public int unstableCount;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004098
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004099 // When this is set, the stable and unstable ref counts are 0 and
4100 // we have a pending operation scheduled to remove the ref count
4101 // from the activity manager. On the activity manager we are still
4102 // holding an unstable ref, though it is not reflected in the counts
4103 // here.
4104 public boolean removePending;
4105
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004106 ProviderRefCount(ContentProviderHolder inHolder,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004107 ProviderClientRecord inClient, int sCount, int uCount) {
4108 holder = inHolder;
4109 client = inClient;
4110 stableCount = sCount;
4111 unstableCount = uCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 }
4113 }
4114
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004115 /**
4116 * Core implementation of stopping an activity. Note this is a little
4117 * tricky because the server's meaning of stop is slightly different
4118 * than our client -- for the server, stop means to save state and give
4119 * it the result when it is done, but the window may still be visible.
4120 * For the client, we want to call onStop()/onStart() to indicate when
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004121 * the activity's UI visibility changes.
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004122 */
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004123 private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
4124 boolean saveState, String reason) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004125 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 if (r != null) {
4127 if (!keepShown && r.stopped) {
4128 if (r.activity.mFinished) {
4129 // If we are finishing, we won't call onResume() in certain
4130 // cases. So here we likewise don't want to call onStop()
4131 // if the activity isn't resumed.
4132 return;
4133 }
4134 RuntimeException e = new RuntimeException(
Andrii Kulian58178f22016-03-16 13:44:56 -07004135 "Performing stop of activity that is already stopped: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004137 Slog.e(TAG, e.getMessage(), e);
Andrii Kulian58178f22016-03-16 13:44:56 -07004138 Slog.e(TAG, r.getStateString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 }
4140
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004141 // One must first be paused before stopped...
4142 performPauseActivityIfNeeded(r, reason);
4143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 if (info != null) {
4145 try {
4146 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07004147 // For now, don't create the thumbnail here; we are
4148 // doing that by doing a screen snapshot.
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004149 info.setDescription(r.activity.onCreateDescription());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 } catch (Exception e) {
4151 if (!mInstrumentation.onException(r.activity, e)) {
4152 throw new RuntimeException(
4153 "Unable to save state of activity "
4154 + r.intent.getComponent().toShortString()
4155 + ": " + e.toString(), e);
4156 }
4157 }
4158 }
4159
4160 if (!keepShown) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004161 callActivityOnStop(r, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 }
4164 }
4165
Andrii Kulian8ae79572018-01-26 15:36:06 -08004166 /**
4167 * Calls {@link Activity#onStop()} and {@link Activity#onSaveInstanceState(Bundle)}, and updates
4168 * the client record's state.
4169 * All calls to stop an activity must be done through this method to make sure that
4170 * {@link Activity#onSaveInstanceState(Bundle)} is also executed in the same call.
4171 */
4172 private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
Andrii Kulian391161f2018-01-29 10:50:02 -08004173 // Before P onSaveInstanceState was called before onStop, starting with P it's
4174 // called after. Before Honeycomb state was always saved before onPause.
Andrii Kulian8ae79572018-01-26 15:36:06 -08004175 final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
4176 && !r.isPreHoneycomb();
Andrii Kulian391161f2018-01-29 10:50:02 -08004177 final boolean isPreP = r.isPreP();
4178 if (shouldSaveState && isPreP) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004179 callActivityOnSaveInstanceState(r);
4180 }
4181
4182 try {
4183 r.activity.performStop(false /*preserveWindow*/);
4184 } catch (SuperNotCalledException e) {
4185 throw e;
4186 } catch (Exception e) {
4187 if (!mInstrumentation.onException(r.activity, e)) {
4188 throw new RuntimeException(
4189 "Unable to stop activity "
4190 + r.intent.getComponent().toShortString()
4191 + ": " + e.toString(), e);
4192 }
4193 }
4194 r.setState(ON_STOP);
4195 EventLog.writeEvent(LOG_AM_ON_STOP_CALLED, UserHandle.myUserId(),
4196 r.activity.getComponentName().getClassName(), reason);
Andrii Kulian391161f2018-01-29 10:50:02 -08004197
4198 if (shouldSaveState && !isPreP) {
4199 callActivityOnSaveInstanceState(r);
4200 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004201 }
4202
Romain Guy65b345f2011-07-27 18:51:50 -07004203 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 View v = r.activity.mDecor;
4205 if (v != null) {
4206 if (show) {
4207 if (!r.activity.mVisibleFromServer) {
4208 r.activity.mVisibleFromServer = true;
4209 mNumVisibleActivities++;
4210 if (r.activity.mVisibleFromClient) {
4211 r.activity.makeVisible();
4212 }
4213 }
4214 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004215 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004216 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Adam Lesinski082614c2016-03-04 14:33:47 -08004217 + r.activityInfo.name + " with new config "
4218 + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 r.newConfig = null;
4220 }
4221 } else {
4222 if (r.activity.mVisibleFromServer) {
4223 r.activity.mVisibleFromServer = false;
4224 mNumVisibleActivities--;
4225 v.setVisibility(View.INVISIBLE);
4226 }
4227 }
4228 }
4229 }
4230
Andrii Kulian446e8242017-10-26 15:17:29 -07004231 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004232 public void handleStopActivity(IBinder token, boolean show, int configChanges,
4233 PendingTransactionActions pendingActions) {
4234 final ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 r.activity.mConfigChangeFlags |= configChanges;
4236
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004237 final StopInfo stopInfo = new StopInfo();
4238 performStopActivityInner(r, stopInfo, show, true, "handleStopActivity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004240 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 TAG, "Finishing stop of " + r + ": show=" + show
4242 + " win=" + r.window);
4243
4244 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07004245
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004246 // Make sure any pending writes are now committed.
4247 if (!r.isPreHoneycomb()) {
4248 QueuedWork.waitToFinish();
4249 }
4250
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004251 stopInfo.setActivity(r);
4252 stopInfo.setState(r.state);
4253 stopInfo.setPersistentState(r.persistentState);
4254 pendingActions.setStopInfo(stopInfo);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004255 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004256 }
4257
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004258 /**
4259 * Schedule the call to tell the activity manager we have stopped. We don't do this
4260 * immediately, because we want to have a chance for any other pending work (in particular
4261 * memory trim requests) to complete before you tell the activity manager to proceed and allow
4262 * us to go fully into the background.
4263 */
4264 @Override
4265 public void reportStop(PendingTransactionActions pendingActions) {
4266 mH.post(pendingActions.getStopInfo());
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004267 }
4268
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004269 @Override
4270 public void performRestartActivity(IBinder token, boolean start) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004271 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 if (r.stopped) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004273 r.activity.performRestart(start);
4274 if (start) {
4275 r.setState(ON_START);
4276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 }
4278 }
4279
Andrii Kulian446e8242017-10-26 15:17:29 -07004280 @Override
4281 public void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004282 ActivityClientRecord r = mActivities.get(token);
Tim Murraye1e6c662015-04-07 13:24:14 -07004283
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08004284 if (r == null) {
4285 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
4286 return;
4287 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 if (!show && !r.stopped) {
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004290 performStopActivityInner(r, null, show, false, "handleWindowVisibility");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 } else if (show && r.stopped) {
4292 // If we are getting ready to gc after going to the background, well
4293 // we are back active so skip it.
4294 unscheduleGcIdler();
4295
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004296 r.activity.performRestart(true /* start */);
4297 r.setState(ON_START);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 }
4299 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07004300 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 TAG, "Handle window " + r + " visibility: " + show);
4302 updateVisibility(r, show);
4303 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004304 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 }
4306
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004307 // TODO: This method should be changed to use {@link #performStopActivityInner} to perform to
4308 // stop operation on the activity to reduce code duplication and the chance of fixing a bug in
4309 // one place and missing the other.
Romain Guy65b345f2011-07-27 18:51:50 -07004310 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004311 ActivityClientRecord r = mActivities.get(token);
4312
4313 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004314 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004315 return;
4316 }
4317
4318 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004319 if (!r.stopped && !r.isPreHoneycomb()) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004320 callActivityOnStop(r, true /* saveState */, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004321 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004322
4323 // Make sure any pending writes are now committed.
4324 if (!r.isPreHoneycomb()) {
4325 QueuedWork.waitToFinish();
4326 }
4327
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004328 // Tell activity manager we slept.
4329 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004330 ActivityManager.getService().activitySlept(r.token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004331 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004332 throw ex.rethrowFromSystemServer();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004333 }
4334 } else {
4335 if (r.stopped && r.activity.mVisibleFromServer) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004336 r.activity.performRestart(true /* start */);
4337 r.setState(ON_START);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004338 }
4339 }
4340 }
4341
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004342 private void handleSetCoreSettings(Bundle coreSettings) {
Craig Mautner88c05892013-06-28 09:47:45 -07004343 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004344 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004345 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004346 onCoreSettingsChange();
4347 }
4348
4349 private void onCoreSettingsChange() {
4350 boolean debugViewAttributes =
4351 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
4352 if (debugViewAttributes != View.mDebugViewAttributes) {
4353 View.mDebugViewAttributes = debugViewAttributes;
4354
4355 // request all activities to relaunch for the changes to take place
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004356 requestRelaunchAllActivities();
4357 }
4358 }
4359
4360 private void requestRelaunchAllActivities() {
4361 for (Map.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
4362 final Activity activity = entry.getValue().activity;
4363 if (!activity.mFinished) {
4364 try {
4365 ActivityManager.getService().requestActivityRelaunch(entry.getKey());
4366 } catch (RemoteException e) {
4367 throw e.rethrowFromSystemServer();
4368 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004369 }
4370 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004371 }
4372
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004373 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00004374 LoadedApk apk = peekPackageInfo(data.pkg, false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004375 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004376 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004377 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00004378 apk = peekPackageInfo(data.pkg, true);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004379 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004380 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004381 }
4382 handleConfigurationChanged(mConfiguration, data.info);
Jeff Brown98365d72012-08-19 20:30:52 -07004383 WindowManagerGlobal.getInstance().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004384 }
4385
Romain Guy65b345f2011-07-27 18:51:50 -07004386 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 final int N = results.size();
4388 for (int i=0; i<N; i++) {
4389 ResultInfo ri = results.get(i);
4390 try {
4391 if (ri.mData != null) {
4392 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004393 ri.mData.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004395 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07004396 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 r.activity.dispatchActivityResult(ri.mResultWho,
4398 ri.mRequestCode, ri.mResultCode, ri.mData);
4399 } catch (Exception e) {
4400 if (!mInstrumentation.onException(r.activity, e)) {
4401 throw new RuntimeException(
4402 "Failure delivering result " + ri + " to activity "
4403 + r.intent.getComponent().toShortString()
4404 + ": " + e.toString(), e);
4405 }
4406 }
4407 }
4408 }
4409
Andrii Kulian446e8242017-10-26 15:17:29 -07004410 @Override
4411 public void handleSendResult(IBinder token, List<ResultInfo> results) {
4412 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004413 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 if (r != null) {
4415 final boolean resumed = !r.paused;
4416 if (!r.activity.mFinished && r.activity.mDecor != null
4417 && r.hideForNow && resumed) {
4418 // We had hidden the activity because it started another
4419 // one... we have gotten a result back and we are not
4420 // paused, so make sure our window is visible.
4421 updateVisibility(r, true);
4422 }
4423 if (resumed) {
4424 try {
4425 // Now we are idle.
4426 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004427 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 mInstrumentation.callActivityOnPause(r.activity);
4429 if (!r.activity.mCalled) {
4430 throw new SuperNotCalledException(
4431 "Activity " + r.intent.getComponent().toShortString()
4432 + " did not call through to super.onPause()");
4433 }
4434 } catch (SuperNotCalledException e) {
4435 throw e;
4436 } catch (Exception e) {
4437 if (!mInstrumentation.onException(r.activity, e)) {
4438 throw new RuntimeException(
4439 "Unable to pause activity "
4440 + r.intent.getComponent().toShortString()
4441 + ": " + e.toString(), e);
4442 }
4443 }
4444 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07004445 checkAndBlockForNetworkAccess();
Andrii Kulian446e8242017-10-26 15:17:29 -07004446 deliverResults(r, results);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 if (resumed) {
Dake Gu67decfa2017-12-27 11:48:08 -08004448 r.activity.performResume(false);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004449 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 }
4451 }
4452 }
4453
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004454 /** Core implementation of activity destroy call. */
4455 ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004457 ActivityClientRecord r = mActivities.get(token);
Craig Mautner88c05892013-06-28 09:47:45 -07004458 Class<? extends Activity> activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004459 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004460 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004461 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 r.activity.mConfigChangeFlags |= configChanges;
4463 if (finishing) {
4464 r.activity.mFinished = true;
4465 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004466
4467 performPauseActivityIfNeeded(r, "destroy");
4468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 if (!r.stopped) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004470 callActivityOnStop(r, false /* saveState */, "destroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004471 }
4472 if (getNonConfigInstance) {
4473 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004474 r.lastNonConfigurationInstances
4475 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 } catch (Exception e) {
4477 if (!mInstrumentation.onException(r.activity, e)) {
4478 throw new RuntimeException(
4479 "Unable to retain activity "
4480 + r.intent.getComponent().toShortString()
4481 + ": " + e.toString(), e);
4482 }
4483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 }
4485 try {
4486 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004487 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 if (!r.activity.mCalled) {
4489 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004490 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 " did not call through to super.onDestroy()");
4492 }
4493 if (r.window != null) {
4494 r.window.closeAllPanels();
4495 }
4496 } catch (SuperNotCalledException e) {
4497 throw e;
4498 } catch (Exception e) {
4499 if (!mInstrumentation.onException(r.activity, e)) {
4500 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004501 "Unable to destroy activity " + safeToComponentShortString(r.intent)
4502 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 }
4504 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004505 r.setState(ON_DESTROY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004508 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 return r;
4510 }
4511
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004512 private static String safeToComponentShortString(Intent intent) {
4513 ComponentName component = intent.getComponent();
4514 return component == null ? "[Unknown]" : component.toShortString();
4515 }
4516
Andrii Kulian446e8242017-10-26 15:17:29 -07004517 @Override
4518 public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
4519 boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004520 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004521 configChanges, getNonConfigInstance);
4522 if (r != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004523 cleanUpPendingRemoveWindows(r, finishing);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524 WindowManager wm = r.activity.getWindowManager();
4525 View v = r.activity.mDecor;
4526 if (v != null) {
4527 if (r.activity.mVisibleFromServer) {
4528 mNumVisibleActivities--;
4529 }
4530 IBinder wtoken = v.getWindowToken();
4531 if (r.activity.mWindowAdded) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004532 if (r.mPreserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004533 // Hold off on removing this until the new activity's
4534 // window is being added.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004535 r.mPendingRemoveWindow = r.window;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004536 r.mPendingRemoveWindowManager = wm;
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004537 // We can only keep the part of the view hierarchy that we control,
4538 // everything else must be removed, because it might not be able to
4539 // behave properly when activity is relaunching.
4540 r.window.clearContentView();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004541 } else {
4542 wm.removeViewImmediate(v);
4543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004545 if (wtoken != null && r.mPendingRemoveWindow == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004546 WindowManagerGlobal.getInstance().closeAll(wtoken,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004547 r.activity.getClass().getName(), "Activity");
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004548 } else if (r.mPendingRemoveWindow != null) {
4549 // We're preserving only one window, others should be closed so app views
4550 // will be detached before the final tear down. It should be done now because
4551 // some components (e.g. WebView) rely on detach callbacks to perform receiver
4552 // unregister and other cleanup.
4553 WindowManagerGlobal.getInstance().closeAllExceptView(token, v,
4554 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004555 }
4556 r.activity.mDecor = null;
4557 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004558 if (r.mPendingRemoveWindow == null) {
4559 // If we are delaying the removal of the activity window, then
4560 // we can't clean up all windows here. Note that we can't do
4561 // so later either, which means any windows that aren't closed
4562 // by the app will leak. Well we try to warning them a lot
4563 // about leaking windows, because that is a bug, so if they are
4564 // using this recreate facility then they get to live with leaks.
Jeff Brown98365d72012-08-19 20:30:52 -07004565 WindowManagerGlobal.getInstance().closeAll(token,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004566 r.activity.getClass().getName(), "Activity");
4567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568
4569 // Mocked out contexts won't be participating in the normal
4570 // process lifecycle, but if we're running with a proper
4571 // ApplicationContext we need to have it tear down things
4572 // cleanly.
4573 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08004574 if (c instanceof ContextImpl) {
4575 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 r.activity.getClass().getName(), "Activity");
4577 }
4578 }
4579 if (finishing) {
4580 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004581 ActivityManager.getService().activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004583 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 }
4585 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004586 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 }
4588
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004589 /**
4590 * @param preserveWindow Whether the activity should try to reuse the window it created,
4591 * including the decor view after the relaunch.
4592 */
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004593 public final void requestRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -08004594 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004595 int configChanges, boolean notResumed, Configuration config,
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004596 Configuration overrideConfig, boolean fromServer, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004597 ActivityClientRecord target = null;
4598
Craig Mautner88c05892013-06-28 09:47:45 -07004599 synchronized (mResourcesManager) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004600 for (int i=0; i<mRelaunchingActivities.size(); i++) {
4601 ActivityClientRecord r = mRelaunchingActivities.get(i);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004602 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004603 if (r.token == token) {
4604 target = r;
4605 if (pendingResults != null) {
4606 if (r.pendingResults != null) {
4607 r.pendingResults.addAll(pendingResults);
4608 } else {
4609 r.pendingResults = pendingResults;
4610 }
4611 }
4612 if (pendingNewIntents != null) {
4613 if (r.pendingIntents != null) {
4614 r.pendingIntents.addAll(pendingNewIntents);
4615 } else {
4616 r.pendingIntents = pendingNewIntents;
4617 }
4618 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004619
4620 // For each relaunch request, activity manager expects an answer
4621 if (!r.onlyLocalRequest && fromServer) {
4622 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004623 ActivityManager.getService().activityRelaunched(token);
Jorim Jaggife89d122015-12-22 16:28:44 +01004624 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004625 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01004626 }
4627 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004628 break;
4629 }
4630 }
4631
4632 if (target == null) {
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004633 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null, fromServer:"
4634 + fromServer);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004635 target = new ActivityClientRecord();
4636 target.token = token;
4637 target.pendingResults = pendingResults;
4638 target.pendingIntents = pendingNewIntents;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004639 target.mPreserveWindow = preserveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004640 if (!fromServer) {
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004641 final ActivityClientRecord existing = mActivities.get(token);
4642 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + existing);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004643 if (existing != null) {
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004644 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: paused= "
4645 + existing.paused);;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004646 target.startsNotResumed = existing.paused;
Wale Ogunwale93f543c2015-02-17 16:55:03 -08004647 target.overrideConfig = existing.overrideConfig;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004648 }
4649 target.onlyLocalRequest = true;
4650 }
4651 mRelaunchingActivities.add(target);
Jeff Brown9ef09972013-10-15 20:49:59 -07004652 sendMessage(H.RELAUNCH_ACTIVITY, target);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004653 }
4654
4655 if (fromServer) {
4656 target.startsNotResumed = notResumed;
4657 target.onlyLocalRequest = false;
4658 }
4659 if (config != null) {
4660 target.createdConfig = config;
4661 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08004662 if (overrideConfig != null) {
4663 target.overrideConfig = overrideConfig;
4664 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004665 target.pendingConfigChanges |= configChanges;
4666 }
4667 }
4668
Romain Guy65b345f2011-07-27 18:51:50 -07004669 private void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 // If we are getting ready to gc after going to the background, well
4671 // we are back active so skip it.
4672 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004673 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674
4675 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004676 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07004677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004678 // First: make sure we have the most recent configuration and most
4679 // recent version of the activity, or skip it if some previous call
4680 // had taken a more recent version.
Craig Mautner88c05892013-06-28 09:47:45 -07004681 synchronized (mResourcesManager) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 int N = mRelaunchingActivities.size();
4683 IBinder token = tmp.token;
4684 tmp = null;
4685 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004686 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 if (r.token == token) {
4688 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004689 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690 mRelaunchingActivities.remove(i);
4691 i--;
4692 N--;
4693 }
4694 }
Bob Leee5408332009-09-04 18:31:17 -07004695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004697 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 return;
4699 }
Bob Leee5408332009-09-04 18:31:17 -07004700
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004701 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
4702 + tmp.token + " with configChanges=0x"
4703 + Integer.toHexString(configChanges));
4704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 if (mPendingConfiguration != null) {
4706 changedConfig = mPendingConfiguration;
4707 mPendingConfiguration = null;
4708 }
4709 }
Bob Leee5408332009-09-04 18:31:17 -07004710
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004711 if (tmp.createdConfig != null) {
4712 // If the activity manager is passing us its current config,
4713 // assume that is really what we want regardless of what we
4714 // may have pending.
4715 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004716 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
4717 && mConfiguration.diff(tmp.createdConfig) != 0)) {
4718 if (changedConfig == null
4719 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
4720 changedConfig = tmp.createdConfig;
4721 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004722 }
4723 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004724
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004725 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004726 + tmp.token + ": changedConfig=" + changedConfig);
Tim Murraye1e6c662015-04-07 13:24:14 -07004727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004728 // If there was a pending configuration change, execute it first.
4729 if (changedConfig != null) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -07004730 mCurDefaultDisplayDpi = changedConfig.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07004731 updateDefaultDensity();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004732 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 }
Bob Leee5408332009-09-04 18:31:17 -07004734
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004735 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004736 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 if (r == null) {
Jorim Jaggife89d122015-12-22 16:28:44 +01004738 if (!tmp.onlyLocalRequest) {
4739 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004740 ActivityManager.getService().activityRelaunched(tmp.token);
Jorim Jaggife89d122015-12-22 16:28:44 +01004741 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004742 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01004743 }
4744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 return;
4746 }
Bob Leee5408332009-09-04 18:31:17 -07004747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004749 r.onlyLocalRequest = tmp.onlyLocalRequest;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004750 r.mPreserveWindow = tmp.mPreserveWindow;
Bob Leee5408332009-09-04 18:31:17 -07004751
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004752 r.activity.mChangingConfigurations = true;
4753
Robert Carr23fa16b2016-01-13 13:19:58 -08004754 // If we are preserving the main window across relaunches we would also like to preserve
4755 // the children. However the client side view system does not support preserving
4756 // the child views so we notify the window manager to expect these windows to
4757 // be replaced and defer requests to destroy or hide them. This way we can achieve
4758 // visual continuity. It's important that we do this here prior to pause and destroy
4759 // as that is when we may hide or remove the child views.
Robert Carr77bdfb52016-05-02 18:18:31 -07004760 //
4761 // There is another scenario, if we have decided locally to relaunch the app from a
4762 // call to recreate, then none of the windows will be prepared for replacement or
4763 // preserved by the server, so we want to notify it that we are preparing to replace
4764 // everything
Robert Carr23fa16b2016-01-13 13:19:58 -08004765 try {
Robert Carr77bdfb52016-05-02 18:18:31 -07004766 if (r.mPreserveWindow || r.onlyLocalRequest) {
4767 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
4768 r.token, !r.onlyLocalRequest);
Robert Carr23fa16b2016-01-13 13:19:58 -08004769 }
4770 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004771 throw e.rethrowFromSystemServer();
Robert Carr23fa16b2016-01-13 13:19:58 -08004772 }
4773
Dianne Hackborne2b04802010-12-09 09:24:55 -08004774 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004775 if (!r.paused) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004776 performPauseActivity(r, false, "handleRelaunchActivity",
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004777 null /* pendingActions */);
Dianne Hackborne2b04802010-12-09 09:24:55 -08004778 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004779 if (!r.stopped) {
4780 callActivityOnStop(r, true /* saveState */, "handleRelaunchActivity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004781 }
Bob Leee5408332009-09-04 18:31:17 -07004782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07004784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004785 r.activity = null;
4786 r.window = null;
4787 r.hideForNow = false;
4788 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07004789 // Merge any pending results and pending intents; don't just replace them
4790 if (tmp.pendingResults != null) {
4791 if (r.pendingResults == null) {
4792 r.pendingResults = tmp.pendingResults;
4793 } else {
4794 r.pendingResults.addAll(tmp.pendingResults);
4795 }
4796 }
4797 if (tmp.pendingIntents != null) {
4798 if (r.pendingIntents == null) {
4799 r.pendingIntents = tmp.pendingIntents;
4800 } else {
4801 r.pendingIntents.addAll(tmp.pendingIntents);
4802 }
4803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 r.startsNotResumed = tmp.startsNotResumed;
Wale Ogunwale60454db2015-01-23 16:05:07 -08004805 r.overrideConfig = tmp.overrideConfig;
Bob Leee5408332009-09-04 18:31:17 -07004806
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004807 // TODO(lifecycler): Move relaunch to lifecycler.
4808 PendingTransactionActions pendingActions = new PendingTransactionActions();
4809 handleLaunchActivity(r, pendingActions);
4810 handleStartActivity(r, pendingActions);
4811 handleResumeActivity(r.token, false /* clearHide */, r.isForward, "relaunch");
4812 if (r.startsNotResumed) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004813 performPauseActivity(r, false /* finished */, "relaunch", pendingActions);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004814 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004815
4816 if (!tmp.onlyLocalRequest) {
4817 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004818 ActivityManager.getService().activityRelaunched(r.token);
Jorim Jaggi4846ee32016-01-07 17:39:12 +01004819 if (r.window != null) {
4820 r.window.reportActivityRelaunched();
4821 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004822 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004823 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01004824 }
4825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 }
4827
Andrii Kulian8ae79572018-01-26 15:36:06 -08004828 private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
Craig Mautnera0026042014-04-23 11:45:37 -07004829 r.state = new Bundle();
4830 r.state.setAllowFds(false);
4831 if (r.isPersistable()) {
4832 r.persistentState = new PersistableBundle();
4833 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
4834 r.persistentState);
4835 } else {
4836 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
4837 }
4838 }
4839
Dianne Hackborn73c14162012-09-19 15:45:06 -07004840 ArrayList<ComponentCallbacks2> collectComponentCallbacks(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004842 ArrayList<ComponentCallbacks2> callbacks
4843 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07004844
Craig Mautner88c05892013-06-28 09:47:45 -07004845 synchronized (mResourcesManager) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004846 final int NAPP = mAllApplications.size();
4847 for (int i=0; i<NAPP; i++) {
Dianne Hackborn73c14162012-09-19 15:45:06 -07004848 callbacks.add(mAllApplications.get(i));
4849 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004850 final int NACT = mActivities.size();
4851 for (int i=0; i<NACT; i++) {
4852 ActivityClientRecord ar = mActivities.valueAt(i);
4853 Activity a = ar.activity;
4854 if (a != null) {
4855 Configuration thisConfig = applyConfigCompatMainThread(
4856 mCurDefaultDisplayDpi, newConfig,
Todd Kennedy233a0b12018-01-29 20:30:24 +00004857 ar.packageInfo.getCompatibilityInfo());
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004858 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
4859 // If the activity is currently resumed, its configuration
4860 // needs to change right now.
4861 callbacks.add(a);
4862 } else if (thisConfig != null) {
4863 // Otherwise, we will tell it about the change
4864 // the next time it is resumed or shown. Note that
4865 // the activity manager may, before then, decide the
4866 // activity needs to be destroyed to handle its new
4867 // configuration.
4868 if (DEBUG_CONFIGURATION) {
4869 Slog.v(TAG, "Setting activity "
4870 + ar.activityInfo.name + " newConfig=" + thisConfig);
Romain Guya998dff2012-03-23 18:58:36 -07004871 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004872 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873 }
4874 }
4875 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004876 final int NSVC = mServices.size();
4877 for (int i=0; i<NSVC; i++) {
4878 callbacks.add(mServices.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004879 }
4880 }
4881 synchronized (mProviderMap) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004882 final int NPRV = mLocalProviders.size();
4883 for (int i=0; i<NPRV; i++) {
4884 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004885 }
4886 }
Bob Leee5408332009-09-04 18:31:17 -07004887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 return callbacks;
4889 }
Bob Leee5408332009-09-04 18:31:17 -07004890
Adam Lesinski082614c2016-03-04 14:33:47 -08004891 /**
4892 * Updates the configuration for an Activity. The ActivityClientRecord's
4893 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
4894 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
4895 * the updated Configuration.
4896 * @param r ActivityClientRecord representing the Activity.
4897 * @param newBaseConfig The new configuration to use. This may be augmented with
4898 * {@link ActivityClientRecord#overrideConfig}.
Adam Lesinski082614c2016-03-04 14:33:47 -08004899 */
4900 private void performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004901 Configuration newBaseConfig) {
4902 performConfigurationChangedForActivity(r, newBaseConfig,
4903 r.activity.getDisplay().getDisplayId(), false /* movedToDifferentDisplay */);
4904 }
4905
4906 /**
4907 * Updates the configuration for an Activity. The ActivityClientRecord's
4908 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
4909 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
4910 * the updated Configuration.
4911 * @param r ActivityClientRecord representing the Activity.
4912 * @param newBaseConfig The new configuration to use. This may be augmented with
4913 * {@link ActivityClientRecord#overrideConfig}.
4914 * @param displayId The id of the display where the Activity currently resides.
4915 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004916 * @return {@link Configuration} instance sent to client, null if not sent.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004917 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004918 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004919 Configuration newBaseConfig, int displayId, boolean movedToDifferentDisplay) {
Adam Lesinski082614c2016-03-04 14:33:47 -08004920 r.tmpConfig.setTo(newBaseConfig);
4921 if (r.overrideConfig != null) {
4922 r.tmpConfig.updateFrom(r.overrideConfig);
4923 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004924 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
4925 r.tmpConfig, r.overrideConfig, displayId, movedToDifferentDisplay);
Adam Lesinski082614c2016-03-04 14:33:47 -08004926 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004927 return reportedConfig;
Adam Lesinski082614c2016-03-04 14:33:47 -08004928 }
4929
4930 /**
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07004931 * Creates a new Configuration only if override would modify base. Otherwise returns base.
4932 * @param base The base configuration.
4933 * @param override The update to apply to the base configuration. Can be null.
4934 * @return A Configuration representing base with override applied.
4935 */
4936 private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
4937 @Nullable Configuration override) {
4938 if (override == null) {
4939 return base;
4940 }
4941 Configuration newConfig = new Configuration(base);
4942 newConfig.updateFrom(override);
4943 return newConfig;
4944 }
4945
4946 /**
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004947 * Decides whether to update a component's configuration and whether to inform it.
Adam Lesinski082614c2016-03-04 14:33:47 -08004948 * @param cb The component callback to notify of configuration change.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004949 * @param newConfig The new configuration.
4950 */
4951 private void performConfigurationChanged(ComponentCallbacks2 cb, Configuration newConfig) {
4952 if (!REPORT_TO_ACTIVITY) {
4953 return;
4954 }
4955
4956 // ContextThemeWrappers may override the configuration for that context. We must check and
4957 // apply any overrides defined.
4958 Configuration contextThemeWrapperOverrideConfig = null;
4959 if (cb instanceof ContextThemeWrapper) {
4960 final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
4961 contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
4962 }
4963
4964 // Apply the ContextThemeWrapper override if necessary.
4965 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
4966 // in many places.
4967 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
4968 newConfig, contextThemeWrapperOverrideConfig);
4969 cb.onConfigurationChanged(configToReport);
4970 }
4971
4972 /**
4973 * Decides whether to update an Activity's configuration and whether to inform it.
4974 * @param activity The activity to notify of configuration change.
Adam Lesinski082614c2016-03-04 14:33:47 -08004975 * @param newConfig The new configuration.
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07004976 * @param amOverrideConfig The override config that differentiates the Activity's configuration
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004977 * from the base global configuration. This is supplied by
4978 * ActivityManager.
4979 * @param displayId Id of the display where activity currently resides.
4980 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004981 * @return Configuration sent to client, null if no changes and not moved to different display.
Adam Lesinski082614c2016-03-04 14:33:47 -08004982 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004983 private Configuration performActivityConfigurationChanged(Activity activity,
4984 Configuration newConfig, Configuration amOverrideConfig, int displayId,
4985 boolean movedToDifferentDisplay) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004986 if (activity == null) {
4987 throw new IllegalArgumentException("No activity provided.");
4988 }
4989 final IBinder activityToken = activity.getActivityToken();
4990 if (activityToken == null) {
4991 throw new IllegalArgumentException("Activity token not set. Is the activity attached?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004992 }
Bob Leee5408332009-09-04 18:31:17 -07004993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004994 boolean shouldChangeConfig = false;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004995 if (activity.mCurrentConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004996 shouldChangeConfig = true;
4997 } else {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004998 // If the new config is the same as the config this Activity is already running with and
4999 // the override config also didn't change, then don't bother calling
5000 // onConfigurationChanged.
Bryce Lee658d9842017-07-28 08:33:36 -07005001 final int diff = activity.mCurrentConfig.diffPublicOnly(newConfig);
5002
Andrii Kulian3b3c9142016-07-18 19:15:56 -07005003 if (diff != 0 || !mResourcesManager.isSameResourcesOverrideConfig(activityToken,
5004 amOverrideConfig)) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005005 // Always send the task-level config changes. For system-level configuration, if
5006 // this activity doesn't handle any of the config changes, then don't bother
5007 // calling onConfigurationChanged as we're going to destroy it.
5008 if (!mUpdatingSystemConfig
5009 || (~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005010 || !REPORT_TO_ACTIVITY) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005011 shouldChangeConfig = true;
5012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005013 }
5014 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005015 if (!shouldChangeConfig && !movedToDifferentDisplay) {
5016 // Nothing significant, don't proceed with updating and reporting.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005017 return null;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005018 }
5019
5020 // Propagate the configuration change to ResourcesManager and Activity.
5021
5022 // ContextThemeWrappers may override the configuration for that context. We must check and
5023 // apply any overrides defined.
5024 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
5025
5026 // We only update an Activity's configuration if this is not a global configuration change.
5027 // This must also be done before the callback, or else we violate the contract that the new
5028 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
5029 // Also apply the ContextThemeWrapper override if necessary.
5030 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
5031 // many places.
5032 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
5033 amOverrideConfig, contextThemeWrapperOverrideConfig);
5034 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig,
5035 displayId, movedToDifferentDisplay);
5036
5037 activity.mConfigChangeFlags = 0;
5038 activity.mCurrentConfig = new Configuration(newConfig);
5039
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005040 // Apply the ContextThemeWrapper override if necessary.
5041 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5042 // in many places.
5043 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
5044 contextThemeWrapperOverrideConfig);
5045
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005046 if (!REPORT_TO_ACTIVITY) {
5047 // Not configured to report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005048 return configToReport;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005049 }
5050
5051 if (movedToDifferentDisplay) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005052 activity.dispatchMovedToDisplay(displayId, configToReport);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005053 }
Bob Leee5408332009-09-04 18:31:17 -07005054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 if (shouldChangeConfig) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005056 activity.mCalled = false;
5057 activity.onConfigurationChanged(configToReport);
5058 if (!activity.mCalled) {
5059 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
5060 " did not call through to super.onConfigurationChanged()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061 }
5062 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005063
5064 return configToReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 }
5066
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005067 public final void applyConfigurationToResources(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -07005068 synchronized (mResourcesManager) {
5069 mResourcesManager.applyConfigurationToResourcesLocked(config, null);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005070 }
5071 }
5072
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005073 final Configuration applyCompatConfiguration(int displayDensity) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005074 Configuration config = mConfiguration;
5075 if (mCompatConfiguration == null) {
5076 mCompatConfiguration = new Configuration();
5077 }
5078 mCompatConfiguration.setTo(mConfiguration);
Adam Lesinski082614c2016-03-04 14:33:47 -08005079 if (mResourcesManager.applyCompatConfigurationLocked(displayDensity,
5080 mCompatConfiguration)) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005081 config = mCompatConfiguration;
5082 }
5083 return config;
5084 }
5085
Andrii Kulian446e8242017-10-26 15:17:29 -07005086 @Override
5087 public void handleConfigurationChanged(Configuration config) {
5088 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
5089 mCurDefaultDisplayDpi = config.densityDpi;
5090 mUpdatingSystemConfig = true;
5091 try {
5092 handleConfigurationChanged(config, null /* compat */);
5093 } finally {
5094 mUpdatingSystemConfig = false;
5095 }
5096 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5097 }
5098
5099 private void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005100
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005101 int configDiff = 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005102
Bryce Lee658d9842017-07-28 08:33:36 -07005103 // This flag tracks whether the new configuration is fundamentally equivalent to the
5104 // existing configuration. This is necessary to determine whether non-activity
5105 // callbacks should receive notice when the only changes are related to non-public fields.
5106 // We do not gate calling {@link #performActivityConfigurationChanged} based on this flag
5107 // as that method uses the same check on the activity config override as well.
5108 final boolean equivalent = config != null && mConfiguration != null
5109 && (0 == mConfiguration.diffPublicOnly(config));
Todd Kennedy35a9a382018-01-25 13:25:37 -08005110 final Theme systemTheme = getSystemContext().getTheme();
5111 final Theme systemUiTheme = getSystemUiContext().getTheme();
Bryce Lee658d9842017-07-28 08:33:36 -07005112
Craig Mautner88c05892013-06-28 09:47:45 -07005113 synchronized (mResourcesManager) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005114 if (mPendingConfiguration != null) {
5115 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
5116 config = mPendingConfiguration;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005117 mCurDefaultDisplayDpi = config.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005118 updateDefaultDensity();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005119 }
5120 mPendingConfiguration = null;
5121 }
5122
5123 if (config == null) {
5124 return;
5125 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005126
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005127 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005128 + config);
Craig Mautner88c05892013-06-28 09:47:45 -07005129
5130 mResourcesManager.applyConfigurationToResourcesLocked(config, compat);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005131 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
5132 mResourcesManager.getConfiguration().getLocales());
Craig Mautner88c05892013-06-28 09:47:45 -07005133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134 if (mConfiguration == null) {
5135 mConfiguration = new Configuration();
5136 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005137 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005138 return;
5139 }
Alan Viverettee54d2452015-05-06 10:41:43 -07005140
5141 configDiff = mConfiguration.updateFrom(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005142 config = applyCompatConfiguration(mCurDefaultDisplayDpi);
Alan Viverette395cd012015-08-11 17:27:04 -04005143
Alan Viverette395cd012015-08-11 17:27:04 -04005144 if ((systemTheme.getChangingConfigurations() & configDiff) != 0) {
5145 systemTheme.rebase();
5146 }
Adam Lesinskia82b6262017-03-21 16:56:17 -07005147
Adam Lesinskia82b6262017-03-21 16:56:17 -07005148 if ((systemUiTheme.getChangingConfigurations() & configDiff) != 0) {
5149 systemUiTheme.rebase();
5150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151 }
Dianne Hackborn73c14162012-09-19 15:45:06 -07005152
5153 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(false, config);
5154
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005155 freeTextLayoutCachesIfNeeded(configDiff);
5156
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005157 if (callbacks != null) {
5158 final int N = callbacks.size();
5159 for (int i=0; i<N; i++) {
Andrii Kulian701214b2016-04-07 09:36:33 -07005160 ComponentCallbacks2 cb = callbacks.get(i);
5161 if (cb instanceof Activity) {
5162 // If callback is an Activity - call corresponding method to consider override
5163 // config and avoid onConfigurationChanged if it hasn't changed.
5164 Activity a = (Activity) cb;
5165 performConfigurationChangedForActivity(mActivities.get(a.getActivityToken()),
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005166 config);
Bryce Lee658d9842017-07-28 08:33:36 -07005167 } else if (!equivalent) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005168 performConfigurationChanged(cb, config);
Andrii Kulian701214b2016-04-07 09:36:33 -07005169 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 }
5172 }
5173
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005174 void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
Adam Lesinskid33ef562017-01-19 14:49:59 -08005175 // Updates triggered by package installation go through a package update
5176 // receiver. Here we try to capture ApplicationInfo changes that are
5177 // caused by other sources, such as overlays. That means we want to be as conservative
5178 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
5179 // to see if anything needs to change.
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005180 LoadedApk apk;
5181 LoadedApk resApk;
5182 // Update all affected loaded packages with new package information
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005183 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005184 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005185 apk = ref != null ? ref.get() : null;
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005186 ref = mResourcePackages.get(ai.packageName);
5187 resApk = ref != null ? ref.get() : null;
5188 }
5189 if (apk != null) {
5190 final ArrayList<String> oldPaths = new ArrayList<>();
5191 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
5192 apk.updateApplicationInfo(ai, oldPaths);
5193 }
5194 if (resApk != null) {
5195 final ArrayList<String> oldPaths = new ArrayList<>();
5196 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
5197 resApk.updateApplicationInfo(ai, oldPaths);
5198 }
5199 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005200 // Update all affected Resources objects to use new ResourcesImpl
5201 mResourcesManager.applyNewResourceDirsLocked(ai.sourceDir, ai.resourceDirs);
5202 }
5203
5204 ApplicationPackageManager.configurationChanged();
5205
5206 // Trigger a regular Configuration change event, only with a different assetsSeq number
5207 // so that we actually call through to all components.
Adam Lesinskia82b6262017-03-21 16:56:17 -07005208 // TODO(adamlesinski): Change this to make use of ActivityManager's upcoming ability to
5209 // store configurations per-process.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005210 Configuration newConfig = new Configuration();
Adam Lesinskia82b6262017-03-21 16:56:17 -07005211 newConfig.assetsSeq = (mConfiguration != null ? mConfiguration.assetsSeq : 0) + 1;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005212 handleConfigurationChanged(newConfig, null);
5213
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07005214 requestRelaunchAllActivities();
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005215 }
5216
Romain Guy46bfc482013-08-16 18:38:29 -07005217 static void freeTextLayoutCachesIfNeeded(int configDiff) {
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005218 if (configDiff != 0) {
5219 // Ask text layout engine to free its caches if there is a locale change
5220 boolean hasLocaleConfigChange = ((configDiff & ActivityInfo.CONFIG_LOCALE) != 0);
5221 if (hasLocaleConfigChange) {
5222 Canvas.freeTextLayoutCaches();
5223 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Cleared TextLayout Caches");
5224 }
5225 }
5226 }
5227
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005228 /**
5229 * Handle new activity configuration and/or move to a different display.
Andrii Kulian446e8242017-10-26 15:17:29 -07005230 * @param activityToken Target activity token.
5231 * @param overrideConfig Activity override config.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005232 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
5233 * value didn't change.
5234 */
Andrii Kulian446e8242017-10-26 15:17:29 -07005235 @Override
5236 public void handleActivityConfigurationChanged(IBinder activityToken,
5237 Configuration overrideConfig, int displayId) {
5238 ActivityClientRecord r = mActivities.get(activityToken);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005239 // Check input params.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 if (r == null || r.activity == null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005241 if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 return;
5243 }
Andrii Kulian51c1b672017-04-07 18:39:32 -07005244 final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
5245 && displayId != r.activity.getDisplay().getDisplayId();
Bob Leee5408332009-09-04 18:31:17 -07005246
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005247 // Perform updates.
Andrii Kulian446e8242017-10-26 15:17:29 -07005248 r.overrideConfig = overrideConfig;
Stephen Kiazykf903b732017-03-20 16:23:45 -07005249 final ViewRootImpl viewRoot = r.activity.mDecor != null
5250 ? r.activity.mDecor.getViewRootImpl() : null;
5251
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005252 if (movedToDifferentDisplay) {
5253 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity moved to display, activity:"
5254 + r.activityInfo.name + ", displayId=" + displayId
Andrii Kulian446e8242017-10-26 15:17:29 -07005255 + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005256
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005257 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
5258 mCompatConfiguration, displayId, true /* movedToDifferentDisplay */);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005259 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005260 viewRoot.onMovedToDisplay(displayId, reportedConfig);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005261 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005262 } else {
5263 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Andrii Kulian446e8242017-10-26 15:17:29 -07005264 + r.activityInfo.name + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005265 performConfigurationChangedForActivity(r, mCompatConfiguration);
5266 }
Andrii Kulian44607962017-03-16 11:06:24 -07005267 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
5268 // update to make sure that resources are updated before updating itself.
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005269 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005270 viewRoot.updateConfiguration(displayId);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005271 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005272 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 }
5274
Jeff Hao1b012d32014-08-20 10:35:34 -07005275 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005276 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005277 try {
Romain Guy7eabe552011-07-21 14:56:34 -07005278 switch (profileType) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005279 default:
5280 mProfiler.setProfiler(profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005281 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005282 break;
5283 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005284 } catch (RuntimeException e) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005285 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005286 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07005287 } finally {
Andreas Gampe2b073a02017-06-22 17:28:57 -07005288 profilerInfo.closeFd();
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005289 }
5290 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07005291 switch (profileType) {
Romain Guy7eabe552011-07-21 14:56:34 -07005292 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005293 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005294 break;
Romain Guy7eabe552011-07-21 14:56:34 -07005295 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005296 }
5297 }
Bob Leee5408332009-09-04 18:31:17 -07005298
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005299 /**
5300 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
5301 * so that profiler data won't be lost.
5302 *
5303 * @hide
5304 */
5305 public void stopProfiling() {
Amith Yamasanib1684432017-01-26 14:57:20 -08005306 if (mProfiler != null) {
5307 mProfiler.stopProfiling();
5308 }
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005309 }
5310
Christopher Ferris8d652f82017-04-11 16:29:18 -07005311 static void handleDumpHeap(DumpHeapData dhd) {
Makoto Onuki4556b7b2017-07-07 14:58:58 -07005312 if (dhd.runGc) {
5313 System.gc();
5314 System.runFinalization();
5315 System.gc();
5316 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005317 if (dhd.managed) {
Andy McFadden824c5102010-07-09 16:26:57 -07005318 try {
5319 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
5320 } catch (IOException e) {
5321 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
5322 + " -- can the process access this path?");
5323 } finally {
5324 try {
5325 dhd.fd.close();
5326 } catch (IOException e) {
5327 Slog.w(TAG, "Failure closing profile fd", e);
5328 }
5329 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005330 } else if (dhd.mallocInfo) {
5331 Debug.dumpNativeMallocInfo(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005332 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07005333 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005334 }
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005335 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005336 ActivityManager.getService().dumpHeapFinished(dhd.path);
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005337 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005338 throw e.rethrowFromSystemServer();
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005339 }
Andy McFadden824c5102010-07-09 16:26:57 -07005340 }
5341
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005342 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005343 boolean hasPkgInfo = false;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005344 switch (cmd) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005345 case ApplicationThreadConstants.PACKAGE_REMOVED:
5346 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005347 {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005348 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005349 if (packages == null) {
5350 break;
5351 }
5352 synchronized (mResourcesManager) {
5353 for (int i = packages.length - 1; i >= 0; i--) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005354 if (!hasPkgInfo) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005355 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
5356 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005357 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005358 } else {
5359 ref = mResourcePackages.get(packages[i]);
5360 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005361 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005362 }
5363 }
5364 }
5365 if (killApp) {
5366 mPackages.remove(packages[i]);
5367 mResourcePackages.remove(packages[i]);
5368 }
5369 }
5370 }
5371 break;
5372 }
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005373 case ApplicationThreadConstants.PACKAGE_REPLACED:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005374 {
5375 if (packages == null) {
5376 break;
5377 }
5378 synchronized (mResourcesManager) {
5379 for (int i = packages.length - 1; i >= 0; i--) {
5380 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005381 LoadedApk pkgInfo = ref != null ? ref.get() : null;
5382 if (pkgInfo != null) {
5383 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005384 } else {
5385 ref = mResourcePackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005386 pkgInfo = ref != null ? ref.get() : null;
5387 if (pkgInfo != null) {
5388 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005389 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005390 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005391 // If the package is being replaced, yet it still has a valid
5392 // LoadedApk object, the package was updated with _DONT_KILL.
5393 // Adjust it's internal references to the application info and
5394 // resources.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005395 if (pkgInfo != null) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005396 try {
5397 final String packageName = packages[i];
5398 final ApplicationInfo aInfo =
5399 sPackageManager.getApplicationInfo(
5400 packageName,
Svet Ganov6ce92392017-09-27 16:04:10 -07005401 PackageManager.GET_SHARED_LIBRARY_FILES,
Todd Kennedy39bfee52016-02-24 10:28:21 -08005402 UserHandle.myUserId());
5403
5404 if (mActivities.size() > 0) {
5405 for (ActivityClientRecord ar : mActivities.values()) {
5406 if (ar.activityInfo.applicationInfo.packageName
5407 .equals(packageName)) {
5408 ar.activityInfo.applicationInfo = aInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00005409 ar.packageInfo = pkgInfo;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005410 }
5411 }
5412 }
5413 final List<String> oldPaths =
5414 sPackageManager.getPreviousCodePaths(packageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005415 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
Todd Kennedy39bfee52016-02-24 10:28:21 -08005416 } catch (RemoteException e) {
5417 }
5418 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005419 }
5420 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005421 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005422 }
5423 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00005424 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005425 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 final void handleLowMemory() {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005428 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Bob Leee5408332009-09-04 18:31:17 -07005429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 final int N = callbacks.size();
5431 for (int i=0; i<N; i++) {
5432 callbacks.get(i).onLowMemory();
5433 }
5434
Chris Tatece229052009-03-25 16:44:52 -07005435 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
5436 if (Process.myUid() != Process.SYSTEM_UID) {
5437 int sqliteReleased = SQLiteDatabase.releaseMemory();
5438 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
5439 }
Bob Leee5408332009-09-04 18:31:17 -07005440
Mike Reedcaf0df12009-04-27 14:32:05 -04005441 // Ask graphics to free up as much as possible (font/image caches)
5442 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005444 // Ask text layout engine to free also as much as possible
5445 Canvas.freeTextLayoutCaches();
5446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 BinderInternal.forceGc("mem");
5448 }
5449
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005450 final void handleTrimMemory(int level) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07005451 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005452
Dianne Hackborn73c14162012-09-19 15:45:06 -07005453 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005454
5455 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07005456 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005457 callbacks.get(i).onTrimMemory(level);
5458 }
Romain Guy19f86e82012-04-23 15:19:07 -07005459
John Reckf47a5942014-06-30 16:20:04 -07005460 WindowManagerGlobal.getInstance().trimMemory(level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005461 }
5462
Jesse Hall317fa5a2017-05-23 15:46:55 -07005463 private void setupGraphicsSupport(Context context) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005464 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
Romain Guya9582652011-11-10 14:20:10 -08005465
Jesse Hall317fa5a2017-05-23 15:46:55 -07005466 // The system package doesn't have real data directories, so don't set up cache paths.
5467 if (!"android".equals(context.getPackageName())) {
5468 // This cache location probably points at credential-encrypted
5469 // storage which may not be accessible yet; assign it anyway instead
5470 // of pointing at device-encrypted storage.
5471 final File cacheDir = context.getCacheDir();
5472 if (cacheDir != null) {
5473 // Provide a usable directory for temporary files
5474 System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
5475 } else {
5476 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
5477 + "due to missing cache directory");
Romain Guya9582652011-11-10 14:20:10 -08005478 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005479
5480 // Setup a location to store generated/compiled graphics code.
5481 final Context deviceContext = context.createDeviceProtectedStorageContext();
5482 final File codeCacheDir = deviceContext.getCodeCacheDir();
5483 if (codeCacheDir != null) {
5484 try {
5485 int uid = Process.myUid();
5486 String[] packages = getPackageManager().getPackagesForUid(uid);
5487 if (packages != null) {
Romain Guycecbe072017-07-18 15:42:06 -07005488 ThreadedRenderer.setupDiskCache(codeCacheDir);
5489 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005490 }
5491 } catch (RemoteException e) {
5492 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5493 throw e.rethrowFromSystemServer();
5494 }
5495 } else {
5496 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
5497 }
Romain Guya9582652011-11-10 14:20:10 -08005498 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005499
Cody Northrop86cedcb2017-10-20 09:03:13 -06005500 GraphicsEnvironment.getInstance().setup(context);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005501 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005502 }
5503
5504 private void updateDefaultDensity() {
Alan Viverette2ac46f12016-02-04 16:58:14 -05005505 final int densityDpi = mCurDefaultDisplayDpi;
5506 if (!mDensityCompatMode
5507 && densityDpi != Configuration.DENSITY_DPI_UNDEFINED
5508 && densityDpi != DisplayMetrics.DENSITY_DEVICE) {
5509 DisplayMetrics.DENSITY_DEVICE = densityDpi;
5510 Bitmap.setDefaultDensity(densityDpi);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005511 }
5512 }
5513
Todd Kennedye713efc2016-05-10 13:45:40 -07005514 /**
5515 * Returns the correct library directory for the current ABI.
5516 * <p>
5517 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
5518 * libraries, we might need to choose the secondary depending on what the current
5519 * runtime's instruction set is.
5520 */
5521 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
5522 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null) {
5523 // Get the instruction set supported by the secondary ABI. In the presence
5524 // of a native bridge this might be different than the one secondary ABI used.
5525 String secondaryIsa =
5526 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
5527 final String secondaryDexCodeIsa =
5528 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
5529 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
5530
5531 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
5532 if (runtimeIsa.equals(secondaryIsa)) {
5533 return insInfo.secondaryNativeLibraryDir;
5534 }
5535 }
5536 return insInfo.nativeLibraryDir;
5537 }
5538
Adam Lesinskib61e4052016-05-19 18:23:05 -07005539 /**
5540 * The LocaleList set for the app's resources may have been shuffled so that the preferred
5541 * Locale is at position 0. We must find the index of this preferred Locale in the
5542 * original LocaleList.
5543 */
5544 private void updateLocaleListFromAppContext(Context context, LocaleList newLocaleList) {
5545 final Locale bestLocale = context.getResources().getConfiguration().getLocales().get(0);
5546 final int newLocaleListSize = newLocaleList.size();
5547 for (int i = 0; i < newLocaleListSize; i++) {
5548 if (bestLocale.equals(newLocaleList.get(i))) {
5549 LocaleList.setDefault(newLocaleList, i);
5550 return;
5551 }
5552 }
Adam Lesinski27d30162016-05-25 16:45:14 -07005553
5554 // The app may have overridden the LocaleList with its own Locale
5555 // (not present in the available list). Push the chosen Locale
5556 // to the front of the list.
5557 LocaleList.setDefault(new LocaleList(bestLocale, newLocaleList));
Adam Lesinskib61e4052016-05-19 18:23:05 -07005558 }
5559
Romain Guy65b345f2011-07-27 18:51:50 -07005560 private void handleBindApplication(AppBindData data) {
Calin Juravle8f5770d2016-04-12 14:12:04 +01005561 // Register the UI Thread as a sensitive thread to the runtime.
5562 VMRuntime.registerSensitiveThread();
Man Caocfa78b22015-06-11 20:14:34 -07005563 if (data.trackAllocation) {
5564 DdmVmInternal.enableRecentAllocations(true);
5565 }
5566
Dianne Hackbornd98885c2016-03-01 17:13:03 -08005567 // Note when this process has started.
5568 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
5569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 mBoundApplication = data;
5571 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07005572 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005574 mProfiler = new Profiler();
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005575 String agent = null;
Jeff Hao1b012d32014-08-20 10:35:34 -07005576 if (data.initProfilerInfo != null) {
5577 mProfiler.profileFile = data.initProfilerInfo.profileFile;
5578 mProfiler.profileFd = data.initProfilerInfo.profileFd;
5579 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
5580 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -08005581 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005582 if (data.initProfilerInfo.attachAgentDuringBind) {
5583 agent = data.initProfilerInfo.agent;
5584 }
Jeff Hao1b012d32014-08-20 10:35:34 -07005585 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08005588 Process.setArgV0(data.processName);
Siva Velusamyd693dfa2012-09-10 14:36:58 -07005589 android.ddm.DdmHandleAppName.setAppName(data.processName,
5590 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005592 if (mProfiler.profileFd != null) {
5593 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07005594 }
5595
Joe Onoratod630f102011-03-17 18:42:26 -07005596 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
5597 // implementation to use the pool executor. Normally, we use the
5598 // serialized executor as the default. This has to happen in the
5599 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07005600 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07005601 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
5602 }
5603
Dianne Hackborn7895bc22014-09-05 15:09:03 -07005604 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
5605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 /*
5607 * Before spawning a new process, reset the time zone to be the system time zone.
5608 * This needs to be done because the system time zone could have changed after the
5609 * the spawning of this process. Without doing this this process would have the incorrect
5610 * system time zone.
5611 */
5612 TimeZone.setDefault(null);
5613
Adam Lesinskib61e4052016-05-19 18:23:05 -07005614 /*
5615 * Set the LocaleList. This may change once we create the App Context.
5616 */
5617 LocaleList.setDefault(data.config.getLocales());
5618
5619 synchronized (mResourcesManager) {
5620 /*
5621 * Update the system configuration since its preloaded and might not
5622 * reflect configuration changes. The configuration object passed
5623 * in AppBindData can be safely assumed to be up to date
5624 */
5625 mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
5626 mCurDefaultDisplayDpi = data.config.densityDpi;
5627
5628 // This calls mResourcesManager so keep it within the synchronized block.
5629 applyCompatConfiguration(mCurDefaultDisplayDpi);
5630 }
5631
Todd Kennedy233a0b12018-01-29 20:30:24 +00005632 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005634 if (agent != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005635 handleAttachAgent(agent, data.info);
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005636 }
5637
Dianne Hackborndde331c2012-08-03 14:01:57 -07005638 /**
5639 * Switch this process to density compatibility mode if needed.
5640 */
5641 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
5642 == 0) {
5643 mDensityCompatMode = true;
5644 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
5645 }
5646 updateDefaultDensity();
5647
Neil Fullerc66ec402016-11-14 16:06:42 +00005648 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
5649 Boolean is24Hr = null;
5650 if (use24HourSetting != null) {
5651 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
5652 }
5653 // null : use locale default for 12/24 hour formatting,
5654 // false : use 12 hour format,
5655 // true : use 24 hour format.
Narayan Kamathccb2a0862013-12-19 14:49:36 +00005656 DateFormat.set24HourTimePref(is24Hr);
5657
Jon Miranda836c0a82014-08-11 12:32:26 -07005658 View.mDebugViewAttributes =
5659 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
5660
Jeff Sharkey89182982017-11-01 19:02:56 -06005661 StrictMode.initThreadDefaults(data.appInfo);
5662 StrictMode.initVmDefaults(data.appInfo);
Jeff Sharkey344744b2016-01-28 19:03:30 -07005663
Svet Ganov37e43272016-09-09 16:01:32 -07005664 // We deprecated Build.SERIAL and only apps that target pre NMR1
5665 // SDK can see it. Since access to the serial is now behind a
5666 // permission we push down the value and here we fix it up
5667 // before any app code has been loaded.
5668 try {
5669 Field field = Build.class.getDeclaredField("SERIAL");
5670 field.setAccessible(true);
5671 field.set(Build.class, data.buildSerial);
5672 } catch (NoSuchFieldException | IllegalAccessException e) {
5673 /* ignore */
5674 }
5675
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005676 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 // XXX should have option to change the port.
5678 Debug.changeDebugPort(8100);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005679 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005680 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 + " is waiting for the debugger on port 8100...");
5682
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005683 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 try {
5685 mgr.showWaitingForDebugger(mAppThread, true);
5686 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005687 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 }
5689
5690 Debug.waitForDebugger();
5691
5692 try {
5693 mgr.showWaitingForDebugger(mAppThread, false);
5694 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005695 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 }
5697
5698 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005699 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 + " can be debugged on port 8100...");
5701 }
5702 }
5703
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005704 // Allow application-generated systrace messages if we're debuggable.
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04005705 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
5706 Trace.setAppTracingAllowed(isAppDebuggable);
5707 if (isAppDebuggable && data.enableBinderTracking) {
5708 Binder.enableTracing();
5709 }
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005710
Robert Greenwalt434203a2010-10-11 16:00:27 -07005711 /**
5712 * Initialize the default http proxy in this process for the reasons we set the time zone.
5713 */
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005714 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
Alan Viverettebe64eae2015-09-03 14:56:04 -04005715 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005716 if (b != null) {
5717 // In pre-boot mode (doing initial launch to collect password), not
5718 // all system is up. This includes the connectivity service, so don't
5719 // crash if we can't get it.
Alan Viverettebe64eae2015-09-03 14:56:04 -04005720 final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005721 try {
Paul Jensencee9b512015-05-06 07:32:40 -04005722 final ProxyInfo proxyInfo = service.getProxyForNetwork(null);
Jason Monk207900c2014-04-25 15:00:09 -04005723 Proxy.setHttpProxySystemProperty(proxyInfo);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005724 } catch (RemoteException e) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005725 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005726 throw e.rethrowFromSystemServer();
5727 }
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005728 }
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005729 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Robert Greenwalt434203a2010-10-11 16:00:27 -07005730
Alan Viverette2107d692015-09-03 14:55:27 -04005731 // Instrumentation info affects the class loader, so load it before
5732 // setting up the app context.
5733 final InstrumentationInfo ii;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 if (data.instrumentationName != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 try {
Alan Viverette2107d692015-09-03 14:55:27 -04005736 ii = new ApplicationPackageManager(null, getPackageManager())
5737 .getInstrumentationInfo(data.instrumentationName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 } catch (PackageManager.NameNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 throw new RuntimeException(
Alan Viverette2107d692015-09-03 14:55:27 -04005740 "Unable to find instrumentation info for: " + data.instrumentationName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 }
5742
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005743 mInstrumentationPackageName = ii.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 mInstrumentationAppDir = ii.sourceDir;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005745 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
Todd Kennedye713efc2016-05-10 13:45:40 -07005746 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005747 mInstrumentedAppDir = data.info.getAppDir();
5748 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
5749 mInstrumentedLibDir = data.info.getLibDir();
Alan Viverette2107d692015-09-03 14:55:27 -04005750 } else {
5751 ii = null;
5752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753
Todd Kennedy233a0b12018-01-29 20:30:24 +00005754 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005755 updateLocaleListFromAppContext(appContext,
5756 mResourcesManager.getConfiguration().getLocales());
Seigo Nonakac14dd782016-03-30 23:09:16 +09005757
Jesse Hall317fa5a2017-05-23 15:46:55 -07005758 if (!Process.isIsolated()) {
Jeff Sharkey89182982017-11-01 19:02:56 -06005759 final int oldMask = StrictMode.allowThreadDiskWritesMask();
5760 try {
5761 setupGraphicsSupport(appContext);
5762 } finally {
5763 StrictMode.setThreadPolicyMask(oldMask);
5764 }
Michael Lentine2ba303f2016-02-01 20:44:34 -06005765 }
Michael Lentine03d8f7682016-01-31 15:37:11 -06005766
Calin Juravle37dfc8e2017-03-13 19:02:32 -07005767 // If we use profiles, setup the dex reporter to notify package manager
5768 // of any relevant dex loads. The idle maintenance job will use the information
5769 // reported to optimize the loaded dex files.
5770 // Note that we only need one global reporter per app.
5771 // Make sure we do this before calling onCreate so that we can capture the
5772 // complete application startup.
5773 if (SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false)) {
Calin Juravlef5a7bfc2017-03-13 23:30:30 -07005774 BaseDexClassLoader.setReporter(DexLoadReporter.getInstance());
Calin Juravle37dfc8e2017-03-13 19:02:32 -07005775 }
5776
Chad Brubaker78d47122015-11-17 22:26:58 -08005777 // Install the Network Security Config Provider. This must happen before the application
5778 // code is loaded to prevent issues with instances of TLS objects being created before
5779 // the provider is installed.
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005780 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
Chad Brubaker276ee962016-06-08 12:57:46 -07005781 NetworkSecurityConfigProvider.install(appContext);
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005782 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Chad Brubaker78d47122015-11-17 22:26:58 -08005783
Alan Viverette2107d692015-09-03 14:55:27 -04005784 // Continue loading instrumentation.
5785 if (ii != null) {
Dianne Hackbornf4ef6eb2017-12-07 13:57:21 -08005786 ApplicationInfo instrApp;
5787 try {
5788 instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
5789 UserHandle.myUserId());
5790 } catch (RemoteException e) {
5791 instrApp = null;
5792 }
5793 if (instrApp == null) {
5794 instrApp = new ApplicationInfo();
5795 }
Jeff Sharkey15447792015-11-05 16:18:51 -08005796 ii.copyTo(instrApp);
Fyodor Kupolovaf38b8e2015-12-02 16:16:07 -08005797 instrApp.initForUser(UserHandle.myUserId());
Todd Kennedy233a0b12018-01-29 20:30:24 +00005798 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07005799 appContext.getClassLoader(), false, true, false);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005800 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801
5802 try {
Alan Viverettebe64eae2015-09-03 14:56:04 -04005803 final ClassLoader cl = instrContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04005804 mInstrumentation = (Instrumentation)
5805 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005806 } catch (Exception e) {
5807 throw new RuntimeException(
5808 "Unable to instantiate instrumentation "
5809 + data.instrumentationName + ": " + e.toString(), e);
5810 }
5811
Alan Viverettebe64eae2015-09-03 14:56:04 -04005812 final ComponentName component = new ComponentName(ii.packageName, ii.name);
5813 mInstrumentation.init(this, instrContext, appContext, component,
5814 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005816 if (mProfiler.profileFile != null && !ii.handleProfiling
5817 && mProfiler.profileFd == null) {
5818 mProfiler.handlingProfiling = true;
Alan Viverettebe64eae2015-09-03 14:56:04 -04005819 final File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 file.getParentFile().mkdirs();
5821 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
5822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 } else {
5824 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05005825 mInstrumentation.basicInit(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 }
5827
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005828 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08005829 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Mathieu Chartier24cee072015-01-08 14:42:20 -08005830 } else {
5831 // Small heap, clamp to the current growth limit and let the heap release
5832 // pages after the growth limit to the non growth limit capacity. b/18387825
5833 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005834 }
5835
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005836 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08005837 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005838 // probably end up doing the same disk access.
Kurt Nelson5e154362017-06-29 17:20:56 -07005839 Application app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005840 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
Kurt Nelson571c3f62017-07-10 11:09:04 -07005841 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005843 // If the app is being launched for full backup or restore, bring it up in
5844 // a restricted environment with the base application class.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005845 app = data.info.makeApplication(data.restrictedBackupMode, null);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08005846
5847 // Propagate autofill compat state
5848 app.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);
5849
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005850 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005851
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005852 // don't bring up providers in restricted mode; they may depend on the
5853 // app's custom Application class
5854 if (!data.restrictedBackupMode) {
Jeff Sharkey3e195892016-03-05 19:48:59 -07005855 if (!ArrayUtils.isEmpty(data.providers)) {
5856 installContentProviders(app, data.providers);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005857 // For process that contains content providers, we want to
5858 // ensure that the JIT is enabled "at some point".
5859 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
5860 }
5861 }
5862
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005863 // Do this after providers, since instrumentation tests generally start their
5864 // test thread at this point, and we don't want that racing.
5865 try {
5866 mInstrumentation.onCreate(data.instrumentationArgs);
5867 }
5868 catch (Exception e) {
5869 throw new RuntimeException(
5870 "Exception thrown in onCreate() of "
5871 + data.instrumentationName + ": " + e.toString(), e);
5872 }
Kurt Nelson571c3f62017-07-10 11:09:04 -07005873 try {
5874 mInstrumentation.callApplicationOnCreate(app);
5875 } catch (Exception e) {
5876 if (!mInstrumentation.onException(app, e)) {
5877 throw new RuntimeException(
5878 "Unable to create application " + app.getClass().getName()
5879 + ": " + e.toString(), e);
5880 }
5881 }
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005882 } finally {
Kurt Nelson571c3f62017-07-10 11:09:04 -07005883 // If the app targets < O-MR1, or doesn't change the thread policy
5884 // during startup, clobber the policy to maintain behavior of b/36951662
5885 if (data.appInfo.targetSdkVersion <= Build.VERSION_CODES.O
5886 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
5887 StrictMode.setThreadPolicy(savedPolicy);
Kurt Nelson5e154362017-06-29 17:20:56 -07005888 }
5889 }
5890
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005891 // Preload fonts resources
Seigo Nonaka54084b62017-04-24 14:46:23 -07005892 FontsContract.setApplicationContextForResources(appContext);
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05005893 if (!Process.isIsolated()) {
5894 try {
5895 final ApplicationInfo info =
5896 getPackageManager().getApplicationInfo(
5897 data.appInfo.packageName,
5898 PackageManager.GET_META_DATA /*flags*/,
5899 UserHandle.myUserId());
5900 if (info.metaData != null) {
5901 final int preloadedFontsResource = info.metaData.getInt(
5902 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
5903 if (preloadedFontsResource != 0) {
5904 data.info.getResources().preloadFonts(preloadedFontsResource);
5905 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005906 }
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05005907 } catch (RemoteException e) {
5908 throw e.rethrowFromSystemServer();
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005909 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 }
5912
5913 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005914 IActivityManager am = ActivityManager.getService();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005915 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
5916 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 Debug.stopMethodTracing();
5918 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005919 //Slog.i(TAG, "am: " + ActivityManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005920 // + ", app thr: " + mAppThread);
5921 try {
5922 am.finishInstrumentation(mAppThread, resultCode, results);
5923 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005924 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 }
5926 }
5927
Romain Guy65b345f2011-07-27 18:51:50 -07005928 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 Context context, List<ProviderInfo> providers) {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005930 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931
Romain Guya998dff2012-03-23 18:58:36 -07005932 for (ProviderInfo cpi : providers) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08005933 if (DEBUG_PROVIDER) {
5934 StringBuilder buf = new StringBuilder(128);
5935 buf.append("Pub ");
5936 buf.append(cpi.authority);
5937 buf.append(": ");
5938 buf.append(cpi.name);
5939 Log.i(TAG, buf.toString());
5940 }
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005941 ContentProviderHolder cph = installProvider(context, null, cpi,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005942 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
5943 if (cph != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005944 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 }
5947 }
5948
5949 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005950 ActivityManager.getService().publishContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 getApplicationThread(), results);
5952 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005953 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 }
5955 }
5956
Jeff Sharkey6d515712012-09-20 16:06:08 -07005957 public final IContentProvider acquireProvider(
5958 Context c, String auth, int userId, boolean stable) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07005959 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005960 if (provider != null) {
5961 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 }
5963
Wale Ogunwale1d646122015-04-24 14:45:14 -07005964 // There is a possible race here. Another thread may try to acquire
5965 // the same provider at the same time. When this happens, we want to ensure
5966 // that the first one wins.
5967 // Note that we cannot hold the lock while acquiring and installing the
5968 // provider since it might take a long time to run and it could also potentially
5969 // be re-entrant in the case where the provider is in the same process.
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005970 ContentProviderHolder holder = null;
Wale Ogunwale1d646122015-04-24 14:45:14 -07005971 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005972 holder = ActivityManager.getService().getContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07005973 getApplicationThread(), auth, userId, stable);
5974 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005975 throw ex.rethrowFromSystemServer();
Wale Ogunwale67fe0a42015-04-24 14:44:54 -07005976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 if (holder == null) {
Jeff Sharkey6d515712012-09-20 16:06:08 -07005978 Slog.e(TAG, "Failed to find provider info for " + auth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 return null;
5980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005982 // Install provider will increment the reference count for us, and break
5983 // any ties in the race.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005984 holder = installProvider(c, holder, holder.info,
5985 true /*noisy*/, holder.noReleaseNeeded, stable);
5986 return holder.provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 }
5988
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005989 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
5990 if (stable) {
5991 prc.stableCount += 1;
5992 if (prc.stableCount == 1) {
5993 // We are acquiring a new stable reference on the provider.
5994 int unstableDelta;
5995 if (prc.removePending) {
5996 // We have a pending remove operation, which is holding the
5997 // last unstable reference. At this point we are converting
5998 // that unstable reference to our new stable reference.
5999 unstableDelta = -1;
6000 // Cancel the removal of the provider.
6001 if (DEBUG_PROVIDER) {
6002 Slog.v(TAG, "incProviderRef: stable "
6003 + "snatched provider from the jaws of death");
6004 }
6005 prc.removePending = false;
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006006 // There is a race! It fails to remove the message, which
6007 // will be handled in completeRemoveProvider().
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006008 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6009 } else {
6010 unstableDelta = 0;
6011 }
6012 try {
6013 if (DEBUG_PROVIDER) {
6014 Slog.v(TAG, "incProviderRef Now stable - "
6015 + prc.holder.info.name + ": unstableDelta="
6016 + unstableDelta);
6017 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006018 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006019 prc.holder.connection, 1, unstableDelta);
6020 } catch (RemoteException e) {
6021 //do nothing content provider object is dead any way
6022 }
6023 }
6024 } else {
6025 prc.unstableCount += 1;
6026 if (prc.unstableCount == 1) {
6027 // We are acquiring a new unstable reference on the provider.
6028 if (prc.removePending) {
6029 // Oh look, we actually have a remove pending for the
6030 // provider, which is still holding the last unstable
6031 // reference. We just need to cancel that to take new
6032 // ownership of the reference.
6033 if (DEBUG_PROVIDER) {
6034 Slog.v(TAG, "incProviderRef: unstable "
6035 + "snatched provider from the jaws of death");
6036 }
6037 prc.removePending = false;
6038 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6039 } else {
6040 // First unstable ref, increment our count in the
6041 // activity manager.
6042 try {
6043 if (DEBUG_PROVIDER) {
6044 Slog.v(TAG, "incProviderRef: Now unstable - "
6045 + prc.holder.info.name);
6046 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006047 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006048 prc.holder.connection, 0, 1);
6049 } catch (RemoteException e) {
6050 //do nothing content provider object is dead any way
6051 }
6052 }
6053 }
6054 }
6055 }
6056
Jeff Sharkey6d515712012-09-20 16:06:08 -07006057 public final IContentProvider acquireExistingProvider(
6058 Context c, String auth, int userId, boolean stable) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006059 synchronized (mProviderMap) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006060 final ProviderKey key = new ProviderKey(auth, userId);
Jeff Sharkey6d515712012-09-20 16:06:08 -07006061 final ProviderClientRecord pr = mProviderMap.get(key);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006062 if (pr == null) {
6063 return null;
6064 }
6065
6066 IContentProvider provider = pr.mProvider;
6067 IBinder jBinder = provider.asBinder();
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006068 if (!jBinder.isBinderAlive()) {
6069 // The hosting process of the provider has died; we can't
6070 // use this one.
Wale Ogunwale1d646122015-04-24 14:45:14 -07006071 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006072 + ": existing object's process dead");
6073 handleUnstableProviderDiedLocked(jBinder, true);
6074 return null;
6075 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006076
6077 // Only increment the ref count if we have one. If we don't then the
6078 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006079 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006080 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006081 incProviderRefLocked(prc, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006082 }
6083 return provider;
6084 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006085 }
6086
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006087 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
6088 if (provider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 return false;
6090 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006092 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006093 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006095 if (prc == null) {
6096 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006098 }
6099
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006100 boolean lastRef = false;
6101 if (stable) {
6102 if (prc.stableCount == 0) {
6103 if (DEBUG_PROVIDER) Slog.v(TAG,
6104 "releaseProvider: stable ref count already 0, how?");
6105 return false;
6106 }
6107 prc.stableCount -= 1;
6108 if (prc.stableCount == 0) {
6109 // What we do at this point depends on whether there are
6110 // any unstable refs left: if there are, we just tell the
6111 // activity manager to decrement its stable count; if there
6112 // aren't, we need to enqueue this provider to be removed,
6113 // and convert to holding a single unstable ref while
6114 // doing so.
6115 lastRef = prc.unstableCount == 0;
6116 try {
6117 if (DEBUG_PROVIDER) {
6118 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
6119 + lastRef + " - " + prc.holder.info.name);
6120 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006121 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006122 prc.holder.connection, -1, lastRef ? 1 : 0);
6123 } catch (RemoteException e) {
6124 //do nothing content provider object is dead any way
6125 }
6126 }
6127 } else {
6128 if (prc.unstableCount == 0) {
6129 if (DEBUG_PROVIDER) Slog.v(TAG,
6130 "releaseProvider: unstable ref count already 0, how?");
6131 return false;
6132 }
6133 prc.unstableCount -= 1;
6134 if (prc.unstableCount == 0) {
6135 // If this is the last reference, we need to enqueue
6136 // this provider to be removed instead of telling the
6137 // activity manager to remove it at this point.
6138 lastRef = prc.stableCount == 0;
6139 if (!lastRef) {
6140 try {
6141 if (DEBUG_PROVIDER) {
6142 Slog.v(TAG, "releaseProvider: No longer unstable - "
6143 + prc.holder.info.name);
6144 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006145 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006146 prc.holder.connection, 0, -1);
6147 } catch (RemoteException e) {
6148 //do nothing content provider object is dead any way
6149 }
6150 }
6151 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006152 }
6153
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006154 if (lastRef) {
6155 if (!prc.removePending) {
6156 // Schedule the actual remove asynchronously, since we don't know the context
6157 // this will be called in.
6158 // TODO: it would be nice to post a delayed message, so
6159 // if we come back and need the same provider quickly
6160 // we will still have it available.
6161 if (DEBUG_PROVIDER) {
6162 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
6163 + prc.holder.info.name);
6164 }
6165 prc.removePending = true;
6166 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
6167 mH.sendMessage(msg);
6168 } else {
6169 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
6170 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006171 }
6172 return true;
6173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 }
6175
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006176 final void completeRemoveProvider(ProviderRefCount prc) {
6177 synchronized (mProviderMap) {
6178 if (!prc.removePending) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006179 // There was a race! Some other client managed to acquire
6180 // the provider before the removal was completed.
6181 // Abort the removal. We will do it later.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006182 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006183 + "provider still in use");
6184 return;
6185 }
6186
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006187 // More complicated race!! Some client managed to acquire the
6188 // provider and release it before the removal was completed.
6189 // Continue the removal, and abort the next remove message.
6190 prc.removePending = false;
6191
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006192 final IBinder jBinder = prc.holder.provider.asBinder();
6193 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
6194 if (existingPrc == prc) {
6195 mProviderRefCountMap.remove(jBinder);
6196 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006197
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006198 for (int i=mProviderMap.size()-1; i>=0; i--) {
6199 ProviderClientRecord pr = mProviderMap.valueAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006200 IBinder myBinder = pr.mProvider.asBinder();
6201 if (myBinder == jBinder) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006202 mProviderMap.removeAt(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006203 }
6204 }
6205 }
6206
6207 try {
6208 if (DEBUG_PROVIDER) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006209 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006210 + "removeContentProvider(" + prc.holder.info.name + ")");
6211 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006212 ActivityManager.getService().removeContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006213 prc.holder.connection, false);
6214 } catch (RemoteException e) {
6215 //do nothing content provider object is dead any way
6216 }
6217 }
6218
6219 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006220 synchronized (mProviderMap) {
6221 handleUnstableProviderDiedLocked(provider, fromClient);
6222 }
6223 }
6224
6225 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
6226 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6227 if (prc != null) {
6228 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
6229 + provider + " " + prc.holder.info.name);
6230 mProviderRefCountMap.remove(provider);
You Kimbc74de62013-10-01 00:13:26 +09006231 for (int i=mProviderMap.size()-1; i>=0; i--) {
6232 ProviderClientRecord pr = mProviderMap.valueAt(i);
6233 if (pr != null && pr.mProvider.asBinder() == provider) {
6234 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
6235 mProviderMap.removeAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006236 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006237 }
You Kimbc74de62013-10-01 00:13:26 +09006238
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006239 if (fromClient) {
6240 // We found out about this due to execution in our client
6241 // code. Tell the activity manager about it now, to ensure
6242 // that the next time we go to do anything with the provider
6243 // it knows it is dead (so we don't race with its death
6244 // notification).
6245 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006246 ActivityManager.getService().unstableProviderDied(
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006247 prc.holder.connection);
6248 } catch (RemoteException e) {
6249 //do nothing content provider object is dead any way
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006250 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07006251 }
6252 }
6253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006255 final void appNotRespondingViaProvider(IBinder provider) {
6256 synchronized (mProviderMap) {
6257 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6258 if (prc != null) {
6259 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006260 ActivityManager.getService()
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006261 .appNotRespondingViaProvider(prc.holder.connection);
6262 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006263 throw e.rethrowFromSystemServer();
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006264 }
6265 }
6266 }
6267 }
6268
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006269 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006270 ContentProvider localProvider, ContentProviderHolder holder) {
Andreas Gampe18e99c12015-03-06 15:29:06 -08006271 final String auths[] = holder.info.authority.split(";");
Jeff Sharkey6d515712012-09-20 16:06:08 -07006272 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
6273
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006274 if (provider != null) {
6275 // If this provider is hosted by the core OS and cannot be upgraded,
6276 // then I guess we're okay doing blocking calls to it.
6277 for (String auth : auths) {
6278 switch (auth) {
6279 case ContactsContract.AUTHORITY:
6280 case CallLog.AUTHORITY:
6281 case CallLog.SHADOW_AUTHORITY:
6282 case BlockedNumberContract.AUTHORITY:
6283 case CalendarContract.AUTHORITY:
6284 case Downloads.Impl.AUTHORITY:
Jeff Sharkeycb621622016-11-11 14:04:32 -07006285 case "telephony":
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006286 Binder.allowBlocking(provider.asBinder());
6287 }
6288 }
6289 }
6290
Jeff Sharkey6d515712012-09-20 16:06:08 -07006291 final ProviderClientRecord pcr = new ProviderClientRecord(
6292 auths, provider, localProvider, holder);
6293 for (String auth : auths) {
6294 final ProviderKey key = new ProviderKey(auth, userId);
6295 final ProviderClientRecord existing = mProviderMap.get(key);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006296 if (existing != null) {
6297 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
Jeff Sharkey6d515712012-09-20 16:06:08 -07006298 + " already published as " + auth);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006299 } else {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006300 mProviderMap.put(key, pcr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 }
6302 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006303 return pcr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 }
6305
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006306 /**
6307 * Installs the provider.
6308 *
6309 * Providers that are local to the process or that come from the system server
6310 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
6311 * Other remote providers are reference counted. The initial reference count
6312 * for all reference counted providers is one. Providers that are not reference
6313 * counted do not have a reference count (at all).
6314 *
6315 * This method detects when a provider has already been installed. When this happens,
6316 * it increments the reference count of the existing provider (if appropriate)
6317 * and returns the existing provider. This can happen due to concurrent
6318 * attempts to acquire the same provider.
6319 */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006320 private ContentProviderHolder installProvider(Context context,
6321 ContentProviderHolder holder, ProviderInfo info,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006322 boolean noisy, boolean noReleaseNeeded, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 ContentProvider localProvider = null;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006324 IContentProvider provider;
Dianne Hackborn5f48fca2012-05-30 11:06:31 -07006325 if (holder == null || holder.provider == null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006326 if (DEBUG_PROVIDER || noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006327 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 + info.name);
6329 }
6330 Context c = null;
6331 ApplicationInfo ai = info.applicationInfo;
6332 if (context.getPackageName().equals(ai.packageName)) {
6333 c = context;
6334 } else if (mInitialApplication != null &&
6335 mInitialApplication.getPackageName().equals(ai.packageName)) {
6336 c = mInitialApplication;
6337 } else {
6338 try {
6339 c = context.createPackageContext(ai.packageName,
6340 Context.CONTEXT_INCLUDE_CODE);
6341 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07006342 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 }
6344 }
6345 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006346 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 ai.packageName +
6348 " while loading content provider " +
6349 info.name);
6350 return null;
6351 }
Adam Lesinski4e862812016-11-21 16:02:24 -08006352
6353 if (info.splitName != null) {
6354 try {
6355 c = c.createContextForSplit(info.splitName);
6356 } catch (NameNotFoundException e) {
6357 throw new RuntimeException(e);
6358 }
6359 }
6360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006361 try {
6362 final java.lang.ClassLoader cl = c.getClassLoader();
Todd Kennedy233a0b12018-01-29 20:30:24 +00006363 LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
6364 if (packageInfo == null) {
Jason Monka80bfb52017-11-16 17:15:37 -05006365 // System startup case.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006366 packageInfo = getSystemContext().mPackageInfo;
Jason Monka80bfb52017-11-16 17:15:37 -05006367 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00006368 localProvider = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05006369 .instantiateProvider(cl, info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 provider = localProvider.getIContentProvider();
6371 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006372 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 info.name + " from sourceDir " +
6374 info.applicationInfo.sourceDir);
6375 return null;
6376 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006377 if (DEBUG_PROVIDER) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 TAG, "Instantiating local provider " + info.name);
6379 // XXX Need to create the correct context for this provider.
6380 localProvider.attachInfo(c, info);
6381 } catch (java.lang.Exception e) {
6382 if (!mInstrumentation.onException(null, e)) {
6383 throw new RuntimeException(
6384 "Unable to get provider " + info.name
6385 + ": " + e.toString(), e);
6386 }
6387 return null;
6388 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006389 } else {
6390 provider = holder.provider;
6391 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 + info.name);
6393 }
6394
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006395 ContentProviderHolder retHolder;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006396
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006397 synchronized (mProviderMap) {
6398 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
6399 + " / " + info.name);
6400 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 if (localProvider != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006402 ComponentName cname = new ComponentName(info.packageName, info.name);
6403 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006404 if (pr != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006405 if (DEBUG_PROVIDER) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006406 Slog.v(TAG, "installProvider: lost the race, "
6407 + "using existing local provider");
6408 }
6409 provider = pr.mProvider;
6410 } else {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006411 holder = new ContentProviderHolder(info);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006412 holder.provider = provider;
6413 holder.noReleaseNeeded = true;
6414 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006415 mLocalProviders.put(jBinder, pr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006416 mLocalProvidersByName.put(cname, pr);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006417 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006418 retHolder = pr.mHolder;
6419 } else {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006420 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
6421 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006422 if (DEBUG_PROVIDER) {
6423 Slog.v(TAG, "installProvider: lost the race, updating ref count");
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006424 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006425 // We need to transfer our new reference to the existing
6426 // ref count, releasing the old one... but only if
6427 // release is needed (that is, it is not running in the
6428 // system process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006429 if (!noReleaseNeeded) {
6430 incProviderRefLocked(prc, stable);
Wale Ogunwale1d646122015-04-24 14:45:14 -07006431 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006432 ActivityManager.getService().removeContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07006433 holder.connection, stable);
6434 } catch (RemoteException e) {
6435 //do nothing content provider object is dead any way
6436 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006437 }
6438 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006439 ProviderClientRecord client = installProviderAuthoritiesLocked(
6440 provider, localProvider, holder);
6441 if (noReleaseNeeded) {
6442 prc = new ProviderRefCount(holder, client, 1000, 1000);
6443 } else {
6444 prc = stable
6445 ? new ProviderRefCount(holder, client, 1, 0)
6446 : new ProviderRefCount(holder, client, 0, 1);
6447 }
6448 mProviderRefCountMap.put(jBinder, prc);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006449 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006450 retHolder = prc.holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 }
6452 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006453 return retHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
6455
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04006456 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
6457 try {
6458 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
6459 main.invoke(null, new Object[]{entryPointArgs});
6460 } catch (ReflectiveOperationException e) {
6461 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
6462 }
6463 // The process will be empty after this method returns; exit the VM now.
6464 System.exit(0);
6465 }
6466
Sudheer Shankaf6690102017-10-16 10:20:32 -07006467 private void attach(boolean system, long startSeq) {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08006468 sCurrentActivityThread = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006471 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Craig Mautner88c05892013-06-28 09:47:45 -07006472 @Override
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08006473 public void run() {
6474 ensureJitEnabled();
6475 }
6476 });
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006477 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
6478 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 RuntimeInit.setApplicationObject(mAppThread.asBinder());
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006480 final IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 try {
Sudheer Shankaf6690102017-10-16 10:20:32 -07006482 mgr.attachApplication(mAppThread, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006484 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006486 // Watch for getting close to heap limit.
6487 BinderInternal.addGcWatcher(new Runnable() {
6488 @Override public void run() {
6489 if (!mSomeActivitiesChanged) {
6490 return;
6491 }
6492 Runtime runtime = Runtime.getRuntime();
6493 long dalvikMax = runtime.maxMemory();
6494 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
6495 if (dalvikUsed > ((3*dalvikMax)/4)) {
6496 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
6497 + " total=" + (runtime.totalMemory()/1024)
6498 + " used=" + (dalvikUsed/1024));
6499 mSomeActivitiesChanged = false;
6500 try {
6501 mgr.releaseSomeActivities(mAppThread);
6502 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006503 throw e.rethrowFromSystemServer();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006504 }
6505 }
6506 }
6507 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 } else {
6509 // Don't set application object here -- if the system crashes,
6510 // we can't display an alert, we just want to die die die.
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006511 android.ddm.DdmHandleAppName.setAppName("system_process",
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006512 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 try {
6514 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05006515 mInstrumentation.basicInit(this);
Jeff Browndefd4a62014-03-10 21:24:37 -07006516 ContextImpl context = ContextImpl.createAppContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00006517 this, getSystemContext().mPackageInfo);
6518 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
Jeff Brown7fc8e352014-09-16 18:06:47 -07006519 mInitialApplication.onCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 } catch (Exception e) {
6521 throw new RuntimeException(
6522 "Unable to instantiate Application():" + e.toString(), e);
6523 }
6524 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006525
6526 // add dropbox logging to libcore
6527 DropBox.setReporter(new DropBoxReporter());
6528
Andrii Kulian44607962017-03-16 11:06:24 -07006529 ViewRootImpl.ConfigChangedCallback configChangedCallback
6530 = (Configuration globalConfig) -> {
6531 synchronized (mResourcesManager) {
6532 // We need to apply this change to the resources immediately, because upon returning
6533 // the view hierarchy will be informed about it.
6534 if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
6535 null /* compat */)) {
6536 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
6537 mResourcesManager.getConfiguration().getLocales());
Adam Lesinskib61e4052016-05-19 18:23:05 -07006538
Andrii Kulian44607962017-03-16 11:06:24 -07006539 // This actually changed the resources! Tell everyone about it.
6540 if (mPendingConfiguration == null
6541 || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
6542 mPendingConfiguration = globalConfig;
6543 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006544 }
6545 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006546 }
Andrii Kulian44607962017-03-16 11:06:24 -07006547 };
6548 ViewRootImpl.addConfigCallback(configChangedCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 }
6550
Romain Guy5e9120d2012-01-30 12:17:22 -08006551 public static ActivityThread systemMain() {
Alan Viverette5e1565e2014-07-29 16:14:25 -07006552 // The system process on low-memory devices do not get to use hardware
6553 // accelerated drawing, since this can add too much overhead to the
6554 // process.
6555 if (!ActivityManager.isHighEndGfx()) {
John Reck51aaf902015-12-02 15:08:07 -08006556 ThreadedRenderer.disable(true);
John Reck73840ea2014-09-22 07:39:18 -07006557 } else {
John Reck51aaf902015-12-02 15:08:07 -08006558 ThreadedRenderer.enableForegroundTrimming();
Alan Viverette5e1565e2014-07-29 16:14:25 -07006559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07006561 thread.attach(true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 return thread;
6563 }
6564
Jeff Brown10e89712011-07-08 18:52:57 -07006565 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07006567 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 }
6569 }
6570
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006571 public int getIntCoreSetting(String key, int defaultValue) {
Craig Mautner88c05892013-06-28 09:47:45 -07006572 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08006573 if (mCoreSettings != null) {
6574 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006575 }
Craig Mautner88c05892013-06-28 09:47:45 -07006576 return defaultValue;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006577 }
6578 }
6579
Geremy Condra69689a72012-09-11 16:57:17 -07006580 private static class EventLoggingReporter implements EventLogger.Reporter {
6581 @Override
6582 public void report (int code, Object... list) {
6583 EventLog.writeEvent(code, list);
6584 }
6585 }
6586
Geremy Condrab7faaf42012-09-19 18:07:42 -07006587 private class DropBoxReporter implements DropBox.Reporter {
6588
6589 private DropBoxManager dropBox;
6590
Narayan Kamath7f062242015-04-08 13:24:13 +01006591 public DropBoxReporter() {}
Geremy Condrab7faaf42012-09-19 18:07:42 -07006592
6593 @Override
6594 public void addData(String tag, byte[] data, int flags) {
Narayan Kamath7f062242015-04-08 13:24:13 +01006595 ensureInitialized();
Geremy Condrab7faaf42012-09-19 18:07:42 -07006596 dropBox.addData(tag, data, flags);
6597 }
6598
6599 @Override
6600 public void addText(String tag, String data) {
Narayan Kamath7f062242015-04-08 13:24:13 +01006601 ensureInitialized();
Geremy Condrab7faaf42012-09-19 18:07:42 -07006602 dropBox.addText(tag, data);
6603 }
Narayan Kamath7f062242015-04-08 13:24:13 +01006604
6605 private synchronized void ensureInitialized() {
6606 if (dropBox == null) {
6607 dropBox = (DropBoxManager) getSystemContext().getSystemService(Context.DROPBOX_SERVICE);
6608 }
6609 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006610 }
6611
Romain Guy65b345f2011-07-27 18:51:50 -07006612 public static void main(String[] args) {
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006613 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
Bob Leee5408332009-09-04 18:31:17 -07006614
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08006615 // CloseGuard defaults to true and can be quite spammy. We
6616 // disable it here, but selectively enable it later (via
6617 // StrictMode) on debug builds, but using DropBox, not logs.
6618 CloseGuard.setEnabled(false);
6619
Andreas Gamped281b422016-07-08 03:50:27 +00006620 Environment.initForCurrentUser();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006621
Geremy Condra69689a72012-09-11 16:57:17 -07006622 // Set the reporter for event logging in libcore
6623 EventLogger.setReporter(new EventLoggingReporter());
6624
Robin Lee3d076af2014-04-25 14:57:49 +01006625 // Make sure TrustedCertificateStore looks in the right place for CA certificates
6626 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
6627 TrustedCertificateStore.setDefaultUserDirectory(configDir);
6628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 Process.setArgV0("<pre-initialized>");
6630
6631 Looper.prepareMainLooper();
6632
Sudheer Shankaf6690102017-10-16 10:20:32 -07006633 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
6634 // It will be in the format "seq=114"
6635 long startSeq = 0;
6636 if (args != null) {
6637 for (int i = args.length - 1; i >= 0; --i) {
6638 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
6639 startSeq = Long.parseLong(
6640 args[i].substring(PROC_START_SEQ_IDENT.length()));
6641 }
6642 }
6643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07006645 thread.attach(false, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646
Vairavan Srinivasan7335cfd2012-08-18 18:36:03 -07006647 if (sMainThreadHandler == null) {
6648 sMainThreadHandler = thread.getHandler();
6649 }
6650
Dianne Hackborn287952c2010-09-22 22:34:31 -07006651 if (false) {
6652 Looper.myLooper().setMessageLogging(new
6653 LogPrinter(Log.DEBUG, "ActivityThread"));
6654 }
6655
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006656 // End of event ActivityThreadMain.
6657 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 Looper.loop();
6659
Jeff Brown10e89712011-07-08 18:52:57 -07006660 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
Chris Craikfc294242016-12-13 18:10:46 -08006662
6663 // ------------------ Regular JNI ------------------------
6664
6665 private native void nDumpGraphicsInfo(FileDescriptor fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666}