blob: 4e8d24005da2e538ae6c74b59761886e6b45c484 [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 Kulianb047b8b2017-02-08 18:38:26 -080019import static android.view.Display.INVALID_DISPLAY;
20
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -070021import android.annotation.NonNull;
22import android.annotation.Nullable;
Dianne Hackborn69c6adc2015-06-02 10:52:59 -070023import android.app.assist.AssistContent;
24import android.app.assist.AssistStructure;
Christopher Tate45281862010-03-05 15:46:30 -080025import android.app.backup.BackupAgent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070027import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.ComponentName;
29import android.content.ContentProvider;
30import android.content.Context;
31import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070032import android.content.IIntentReceiver;
Jesse Hall317fa5a2017-05-23 15:46:55 -070033import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.pm.ActivityInfo;
35import android.content.pm.ApplicationInfo;
36import android.content.pm.IPackageManager;
37import android.content.pm.InstrumentationInfo;
Christopher Tate346acb12012-10-15 19:20:25 -070038import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070040import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070041import android.content.pm.ParceledListSlice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ProviderInfo;
43import android.content.pm.ServiceInfo;
44import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070045import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.res.Configuration;
47import android.content.res.Resources;
Alan Viverettee54d2452015-05-06 10:41:43 -070048import android.content.res.Resources.Theme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.database.sqlite.SQLiteDatabase;
50import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080051import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.graphics.Bitmap;
53import android.graphics.Canvas;
Jeff Brownbd6e1502012-08-28 03:27:37 -070054import android.hardware.display.DisplayManagerGlobal;
Paul Jensene0bef712014-12-10 15:12:18 -050055import android.net.ConnectivityManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070056import android.net.IConnectivityManager;
Paul Jensene0bef712014-12-10 15:12:18 -050057import android.net.Network;
Robert Greenwalt434203a2010-10-11 16:00:27 -070058import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040059import android.net.ProxyInfo;
Jason Monk83520b92014-05-09 15:16:06 -040060import android.net.Uri;
Joe Onoratod630f102011-03-17 18:42:26 -070061import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070062import android.os.Binder;
Jeff Sharkey344744b2016-01-28 19:03:30 -070063import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.Bundle;
65import android.os.Debug;
Geremy Condrab7faaf42012-09-19 18:07:42 -070066import android.os.DropBoxManager;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070067import android.os.Environment;
Jesse Hallb12249b2016-12-12 12:53:02 -080068import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Handler;
70import android.os.IBinder;
Adam Lesinskib61e4052016-05-19 18:23:05 -070071import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.Looper;
73import android.os.Message;
74import android.os.MessageQueue;
Dianne Hackbornfabb70b2014-11-11 12:22:36 -080075import android.os.Parcel;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070076import android.os.ParcelFileDescriptor;
Craig Mautnera0026042014-04-23 11:45:37 -070077import android.os.PersistableBundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.os.Process;
79import android.os.RemoteException;
80import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070081import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.SystemClock;
Jeff Brownefd43bd2012-09-21 17:02:35 -070083import android.os.SystemProperties;
Dianne Hackborn1ded0b12012-04-26 14:14:50 -070084import android.os.Trace;
Jeff Sharkey369f5092016-02-29 11:16:21 -070085import android.os.TransactionTooLargeException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070086import android.os.UserHandle;
Jeff Sharkey0a17db12016-11-04 11:23:46 -060087import android.provider.BlockedNumberContract;
88import android.provider.CalendarContract;
89import android.provider.CallLog;
90import android.provider.ContactsContract;
91import android.provider.Downloads;
Seigo Nonaka54084b62017-04-24 14:46:23 -070092import android.provider.FontsContract;
Narayan Kamathccb2a0862013-12-19 14:49:36 +000093import android.provider.Settings;
Jesse Hall317fa5a2017-05-23 15:46:55 -070094import android.renderscript.RenderScriptCacheDir;
Chad Brubakerc72875b2016-04-27 16:35:11 -070095import android.security.NetworkSecurityPolicy;
Chad Brubaker78d47122015-11-17 22:26:58 -080096import android.security.net.config.NetworkSecurityConfigProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.util.AndroidRuntimeException;
Dianne Hackbornadd005c2013-07-17 18:43:12 -070098import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.util.DisplayMetrics;
100import android.util.EventLog;
101import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700102import android.util.LogPrinter;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600103import android.util.LogWriter;
Craig Mautnereb8abf72014-07-02 15:04:09 -0700104import android.util.Pair;
Jeff Brown6754ba22011-12-14 20:20:01 -0800105import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800106import android.util.Slog;
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700107import android.util.SparseIntArray;
Adam Powell14874662013-07-18 19:42:41 -0700108import android.util.SuperNotCalledException;
Adam Lesinski3ad1b482016-04-01 16:41:41 -0700109import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.view.Display;
John Reck51aaf902015-12-02 15:08:07 -0800111import android.view.ThreadedRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.view.View;
113import android.view.ViewDebug;
114import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -0700115import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.view.Window;
117import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700118import android.view.WindowManagerGlobal;
Richard Uhler2c036192016-09-14 09:48:31 +0100119import android.webkit.WebView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700121import com.android.internal.annotations.GuardedBy;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700122import com.android.internal.app.IVoiceInteractor;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800123import com.android.internal.content.ReferrerIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import com.android.internal.os.BinderInternal;
125import com.android.internal.os.RuntimeInit;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700126import com.android.internal.os.SomeArgs;
Jeff Sharkey3e195892016-03-05 19:48:59 -0700127import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -0700128import com.android.internal.util.FastPrintWriter;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600129import com.android.internal.util.IndentingPrintWriter;
Kenny Root12e75222013-04-23 22:34:24 -0700130import com.android.org.conscrypt.OpenSSLSocketImpl;
Robin Lee3d076af2014-04-25 14:57:49 +0100131import com.android.org.conscrypt.TrustedCertificateStore;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700132
133import dalvik.system.BaseDexClassLoader;
134import dalvik.system.CloseGuard;
135import dalvik.system.VMDebug;
136import dalvik.system.VMRuntime;
137
Jesse Hall317fa5a2017-05-23 15:46:55 -0700138import libcore.io.DropBox;
139import libcore.io.EventLogger;
140import libcore.io.IoUtils;
141import libcore.net.event.NetworkEventDispatcher;
142
143import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.io.File;
146import java.io.FileDescriptor;
147import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700148import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.io.PrintWriter;
150import java.lang.ref.WeakReference;
Svet Ganov37e43272016-09-09 16:01:32 -0700151import java.lang.reflect.Field;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400152import java.lang.reflect.Method;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700153import java.net.InetAddress;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000154import java.text.DateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155import java.util.ArrayList;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600156import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157import java.util.List;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700158import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159import java.util.Map;
Kenny Roote6585b32013-12-13 12:00:26 -0800160import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700163final class RemoteServiceException extends AndroidRuntimeException {
164 public RemoteServiceException(String msg) {
165 super(msg);
166 }
167}
168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169/**
170 * This manages the execution of the main thread in an
171 * application process, scheduling and executing activities,
172 * broadcasts, and other operations on it as the activity
173 * manager requests.
174 *
175 * {@hide}
176 */
177public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700178 /** @hide */
179 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700180 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700181 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700182 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700183 /** @hide */
184 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700185 private static final boolean DEBUG_RESULTS = false;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700186 private static final boolean DEBUG_BACKUP = false;
Craig Mautner88c05892013-06-28 09:47:45 -0700187 public static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800188 private static final boolean DEBUG_SERVICE = false;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700189 private static final boolean DEBUG_MEMORY_TRIM = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700190 private static final boolean DEBUG_PROVIDER = false;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700191 private static final boolean DEBUG_ORDER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
Craig Mautnere3119b72015-01-20 15:02:36 -0800194 private static final int LOG_AM_ON_PAUSE_CALLED = 30021;
195 private static final int LOG_AM_ON_RESUME_CALLED = 30022;
Wale Ogunwalecd7043e2016-02-27 17:37:46 -0800196 private static final int LOG_AM_ON_STOP_CALLED = 30049;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Dianne Hackborn455625e2015-01-21 09:55:13 -0800198 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
199 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
200 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
201 public static final int SERVICE_DONE_EXECUTING_START = 1;
202 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
203 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
204
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700205 // Details for pausing activity.
206 private static final int USER_LEAVING = 1;
207 private static final int DONT_REPORT = 2;
208
Filip Gruszczynskica664812015-12-04 12:43:36 -0800209 // Whether to invoke an activity callback after delivering new configuration.
210 private static final boolean REPORT_TO_ACTIVITY = true;
211
Sudheer Shanka84a48952017-03-08 18:19:01 -0800212 /**
213 * Denotes an invalid sequence number corresponding to a process state change.
214 */
215 public static final long INVALID_PROC_STATE_SEQ = -1;
216
217 private final Object mNetworkPolicyLock = new Object();
218
219 /**
220 * Denotes the sequence number of the process state change for which the main thread needs
221 * to block until the network rules are updated for it.
222 *
223 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
224 */
225 @GuardedBy("mNetworkPolicyLock")
226 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
227
Jeff Browndefd4a62014-03-10 21:24:37 -0700228 private ContextImpl mSystemContext;
Adam Lesinskia82b6262017-03-21 16:56:17 -0700229 private ContextImpl mSystemUiContext;
Bob Leee5408332009-09-04 18:31:17 -0700230
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700231 static volatile IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700233 final ApplicationThread mAppThread = new ApplicationThread();
234 final Looper mLooper = Looper.myLooper();
235 final H mH = new H();
Dianne Hackborn782d4982015-07-08 17:36:37 -0700236 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700237 // List of new activities (via ActivityRecord.nextIdle) that should
238 // be reported when next we idle.
239 ActivityClientRecord mNewActivities = null;
240 // Number of activities that are currently visible on-screen.
241 int mNumVisibleActivities = 0;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700242 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
243 private int mLastSessionId;
Dianne Hackborn782d4982015-07-08 17:36:37 -0700244 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700245 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700246 Profiler mProfiler;
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700247 int mCurDefaultDisplayDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -0700248 boolean mDensityCompatMode;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700249 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700250 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700251 Application mInitialApplication;
252 final ArrayList<Application> mAllApplications
253 = new ArrayList<Application>();
254 // set of instantiated backup agents, keyed by package name
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700255 final ArrayMap<String, BackupAgent> mBackupAgents = new ArrayMap<String, BackupAgent>();
Jeff Sharkey66a017b2013-01-17 18:18:22 -0800256 /** Reference to singleton {@link ActivityThread} */
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700257 private static volatile ActivityThread sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700258 Instrumentation mInstrumentation;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700259 String mInstrumentationPackageName = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700260 String mInstrumentationAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700261 String[] mInstrumentationSplitAppDirs = null;
262 String mInstrumentationLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700263 String mInstrumentedAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700264 String[] mInstrumentedSplitAppDirs = null;
265 String mInstrumentedLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700266 boolean mSystemThread = false;
267 boolean mJitEnabled = false;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700268 boolean mSomeActivitiesChanged = false;
Chong Zhang4951f9d2016-06-23 13:15:08 -0700269 boolean mUpdatingSystemConfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100271 // These can be accessed by multiple threads; mResourcesManager is the lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700272 // XXX For now we keep around information about all packages we have
273 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800274 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700275 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800276 // which means this lock gets held while the activity and window managers
277 // holds their own lock. Thus you MUST NEVER call back into the activity manager
278 // or window manager or anything that depends on them while holding this lock.
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700279 // These LoadedApk are only valid for the userId that we're running as.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100280 @GuardedBy("mResourcesManager")
281 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
282 @GuardedBy("mResourcesManager")
283 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
284 @GuardedBy("mResourcesManager")
285 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
286 @GuardedBy("mResourcesManager")
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700287 Configuration mPendingConfiguration = null;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700288 // Because we merge activity relaunch operations we can't depend on the ordering provided by
289 // the handler messages. We need to introduce secondary ordering mechanism, which will allow
290 // us to drop certain events, if we know that they happened before relaunch we already executed.
291 // This represents the order of receiving the request from AM.
292 @GuardedBy("mResourcesManager")
293 int mLifecycleSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
Craig Mautner88c05892013-06-28 09:47:45 -0700295 private final ResourcesManager mResourcesManager;
296
Jeff Sharkey6d515712012-09-20 16:06:08 -0700297 private static final class ProviderKey {
298 final String authority;
299 final int userId;
300
301 public ProviderKey(String authority, int userId) {
302 this.authority = authority;
303 this.userId = userId;
304 }
305
306 @Override
307 public boolean equals(Object o) {
308 if (o instanceof ProviderKey) {
309 final ProviderKey other = (ProviderKey) o;
Kenny Roote6585b32013-12-13 12:00:26 -0800310 return Objects.equals(authority, other.authority) && userId == other.userId;
Jeff Sharkey6d515712012-09-20 16:06:08 -0700311 }
312 return false;
313 }
314
315 @Override
316 public int hashCode() {
317 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
318 }
319 }
320
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700321 // The lock of mProviderMap protects the following variables.
Wale Ogunwale1d646122015-04-24 14:45:14 -0700322 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
323 = new ArrayMap<ProviderKey, ProviderClientRecord>();
324 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
325 = new ArrayMap<IBinder, ProviderRefCount>();
326 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
327 = new ArrayMap<IBinder, ProviderClientRecord>();
328 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
329 = new ArrayMap<ComponentName, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700331 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
Wale Ogunwale1d646122015-04-24 14:45:14 -0700332 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
Jeff Hamilton52d32032011-01-08 15:31:26 -0600333
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700334 final GcIdler mGcIdler = new GcIdler();
335 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700337 static volatile Handler sMainThreadHandler; // set once in main()
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700338
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800339 Bundle mCoreSettings = null;
340
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400341 static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700343 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 Intent intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800345 String referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700346 IVoiceInteractor voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -0700348 PersistableBundle persistentState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 Activity activity;
350 Window window;
351 Activity parent;
352 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700353 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 boolean paused;
355 boolean stopped;
356 boolean hideForNow;
357 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700358 Configuration createdConfig;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800359 Configuration overrideConfig;
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800360 // Used for consolidating configs before sending on to Activity.
361 private Configuration tmpConfig = new Configuration();
Andrii Kulian44607962017-03-16 11:06:24 -0700362 // Callback used for updating activity override config.
363 ViewRootImpl.ActivityConfigCallback configCallback;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700364 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365
Jeff Hao1b012d32014-08-20 10:35:34 -0700366 ProfilerInfo profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400369 CompatibilityInfo compatInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700370 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371
372 List<ResultInfo> pendingResults;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800373 List<ReferrerIntent> pendingIntents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374
375 boolean startsNotResumed;
376 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800377 int pendingConfigChanges;
378 boolean onlyLocalRequest;
379
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700380 Window mPendingRemoveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800381 WindowManager mPendingRemoveWindowManager;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700382 boolean mPreserveWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700384 // Set for relaunch requests, indicates the order number of the relaunch operation, so it
385 // can be compared with other lifecycle operations.
386 int relaunchSeq = 0;
387
388 // Can only be accessed from the UI thread. This represents the latest processed message
389 // that is related to lifecycle events/
390 int lastProcessedSeq = 0;
391
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700392 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 parent = null;
394 embeddedID = null;
395 paused = false;
396 stopped = false;
397 hideForNow = false;
398 nextIdle = null;
Andrii Kulian44607962017-03-16 11:06:24 -0700399 configCallback = (Configuration overrideConfig, int newDisplayId) -> {
400 if (activity == null) {
401 throw new IllegalStateException(
402 "Received config update for non-existing activity");
403 }
404 activity.mMainThread.handleActivityConfigurationChanged(
405 new ActivityConfigChangeData(token, overrideConfig), newDisplayId);
406 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 }
408
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800409 public boolean isPreHoneycomb() {
410 if (activity != null) {
411 return activity.getApplicationInfo().targetSdkVersion
412 < android.os.Build.VERSION_CODES.HONEYCOMB;
413 }
414 return false;
415 }
416
Craig Mautnera0026042014-04-23 11:45:37 -0700417 public boolean isPersistable() {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700418 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
Craig Mautnera0026042014-04-23 11:45:37 -0700419 }
420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 public String toString() {
Dianne Hackbornb61a0262012-05-14 17:19:18 -0700422 ComponentName componentName = intent != null ? intent.getComponent() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 return "ActivityRecord{"
424 + Integer.toHexString(System.identityHashCode(this))
425 + " token=" + token + " " + (componentName == null
426 ? "no component name" : componentName.toShortString())
427 + "}";
428 }
Andrii Kulian58178f22016-03-16 13:44:56 -0700429
430 public String getStateString() {
431 StringBuilder sb = new StringBuilder();
432 sb.append("ActivityClientRecord{");
433 sb.append("paused=").append(paused);
434 sb.append(", stopped=").append(stopped);
435 sb.append(", hideForNow=").append(hideForNow);
436 sb.append(", startsNotResumed=").append(startsNotResumed);
437 sb.append(", isForward=").append(isForward);
438 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
439 sb.append(", onlyLocalRequest=").append(onlyLocalRequest);
440 sb.append(", preserveWindow=").append(mPreserveWindow);
441 if (activity != null) {
442 sb.append(", Activity{");
443 sb.append("resumed=").append(activity.mResumed);
444 sb.append(", stopped=").append(activity.mStopped);
445 sb.append(", finished=").append(activity.isFinishing());
446 sb.append(", destroyed=").append(activity.isDestroyed());
447 sb.append(", startedActivity=").append(activity.mStartedActivity);
448 sb.append(", temporaryPause=").append(activity.mTemporaryPause);
449 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
Andrii Kulian58178f22016-03-16 13:44:56 -0700450 sb.append("}");
451 }
452 sb.append("}");
453 return sb.toString();
454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 }
456
Wale Ogunwale1d646122015-04-24 14:45:14 -0700457 final class ProviderClientRecord {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700458 final String[] mNames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 final IContentProvider mProvider;
460 final ContentProvider mLocalProvider;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700461 final ContentProviderHolder mHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700463 ProviderClientRecord(String[] names, IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700464 ContentProvider localProvider, ContentProviderHolder holder) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700465 mNames = names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 mProvider = provider;
467 mLocalProvider = localProvider;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700468 mHolder = holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 }
470 }
471
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400472 static final class NewIntentData {
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800473 List<ReferrerIntent> intents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 IBinder token;
Wale Ogunwale826c7062016-09-13 08:25:54 -0700475 boolean andPause;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 public String toString() {
Wale Ogunwale826c7062016-09-13 08:25:54 -0700477 return "NewIntentData{intents=" + intents + " token=" + token
478 + " andPause=" + andPause +"}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 }
480 }
481
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400482 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700483 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700484 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
485 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
riddle_hsu1f5ac4d2015-01-03 15:38:21 +0800486 token, sendingUser, intent.getFlags());
Dianne Hackborne829fef2010-10-26 17:44:01 -0700487 this.intent = intent;
488 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 Intent intent;
491 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400492 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 public String toString() {
494 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700495 info.packageName + " resultCode=" + getResultCode()
496 + " resultData=" + getResultData() + " resultExtras="
497 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 }
499 }
500
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400501 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700502 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400503 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700504 int backupMode;
505 public String toString() {
506 return "CreateBackupAgentData{appInfo=" + appInfo
507 + " backupAgent=" + appInfo.backupAgentName
508 + " mode=" + backupMode + "}";
509 }
510 }
Bob Leee5408332009-09-04 18:31:17 -0700511
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400512 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 IBinder token;
514 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400515 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 Intent intent;
517 public String toString() {
518 return "CreateServiceData{token=" + token + " className="
519 + info.name + " packageName=" + info.packageName
520 + " intent=" + intent + "}";
521 }
522 }
523
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400524 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 IBinder token;
526 Intent intent;
527 boolean rebind;
528 public String toString() {
529 return "BindServiceData{token=" + token + " intent=" + intent + "}";
530 }
531 }
532
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400533 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700535 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700537 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 Intent args;
539 public String toString() {
540 return "ServiceArgsData{token=" + token + " startId=" + startId
541 + " args=" + args + "}";
542 }
543 }
544
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400545 static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700546 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 String processName;
548 ApplicationInfo appInfo;
549 List<ProviderInfo> providers;
550 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 Bundle instrumentationArgs;
552 IInstrumentationWatcher instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800553 IUiAutomationConnection instrumentationUiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 int debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400555 boolean enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700556 boolean trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -0700557 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700558 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400560 CompatibilityInfo compatInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700561 String buildSerial;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700562
563 /** Initial values for {@link Profiler}. */
Jeff Hao1b012d32014-08-20 10:35:34 -0700564 ProfilerInfo initProfilerInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 public String toString() {
567 return "AppBindData{appInfo=" + appInfo + "}";
568 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700569 }
570
571 static final class Profiler {
572 String profileFile;
573 ParcelFileDescriptor profileFd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700574 int samplingInterval;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700575 boolean autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800576 boolean streamingOutput;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700577 boolean profiling;
578 boolean handlingProfiling;
Jeff Hao1b012d32014-08-20 10:35:34 -0700579 public void setProfiler(ProfilerInfo profilerInfo) {
580 ParcelFileDescriptor fd = profilerInfo.profileFd;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700581 if (profiling) {
582 if (fd != null) {
583 try {
584 fd.close();
585 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700586 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700587 }
588 }
589 return;
590 }
591 if (profileFd != null) {
592 try {
593 profileFd.close();
594 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700595 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700596 }
597 }
Jeff Hao1b012d32014-08-20 10:35:34 -0700598 profileFile = profilerInfo.profileFile;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700599 profileFd = fd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700600 samplingInterval = profilerInfo.samplingInterval;
601 autoStopProfiler = profilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800602 streamingOutput = profilerInfo.streamingOutput;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700603 }
604 public void startProfiling() {
605 if (profileFd == null || profiling) {
606 return;
607 }
608 try {
Andreas Gampeeff06392016-05-10 12:51:45 -0700609 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
Jeff Hao1b012d32014-08-20 10:35:34 -0700610 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800611 bufferSize * 1024 * 1024, 0, samplingInterval != 0, samplingInterval,
612 streamingOutput);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700613 profiling = true;
614 } catch (RuntimeException e) {
615 Slog.w(TAG, "Profiling failed on path " + profileFile);
616 try {
617 profileFd.close();
618 profileFd = null;
619 } catch (IOException e2) {
620 Slog.w(TAG, "Failure closing profile fd", e2);
621 }
622 }
623 }
624 public void stopProfiling() {
625 if (profiling) {
626 profiling = false;
627 Debug.stopMethodTracing();
628 if (profileFd != null) {
629 try {
630 profileFd.close();
631 } catch (IOException e) {
632 }
633 }
634 profileFd = null;
635 profileFile = null;
636 }
637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 }
639
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400640 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700641 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700642 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800643 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 }
646
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400647 static final class ResultData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 IBinder token;
649 List<ResultInfo> results;
650 public String toString() {
651 return "ResultData{token=" + token + " results" + results + "}";
652 }
653 }
654
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400655 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800656 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 String what;
658 String who;
659 }
660
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400661 static final class DumpHeapData {
Christopher Ferris8d652f82017-04-11 16:29:18 -0700662 public boolean managed;
663 public boolean mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700664 public boolean runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700665 String path;
666 ParcelFileDescriptor fd;
667 }
668
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400669 static final class UpdateCompatibilityData {
670 String pkg;
671 CompatibilityInfo info;
672 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800673
Adam Skorydfc7fd72013-08-05 19:23:41 -0700674 static final class RequestAssistContextExtras {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800675 IBinder activityToken;
676 IBinder requestToken;
677 int requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700678 int sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -0700679 int flags;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800680 }
Anwar Ghuloum3a8ce1b2013-04-26 16:18:28 -0700681
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800682 static final class ActivityConfigChangeData {
683 final IBinder activityToken;
684 final Configuration overrideConfig;
685 public ActivityConfigChangeData(IBinder token, Configuration config) {
686 activityToken = token;
687 overrideConfig = config;
688 }
689 }
690
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700691 private class ApplicationThread extends IApplicationThread.Stub {
Vasu Nori3c7131f2010-09-21 14:36:57 -0700692 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700693
Dianne Hackborna413dc02013-07-12 12:02:55 -0700694 private int mLastProcessState = -1;
695
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700696 private void updatePendingConfiguration(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -0700697 synchronized (mResourcesManager) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700698 if (mPendingConfiguration == null ||
699 mPendingConfiguration.isOtherSeqNewer(config)) {
700 mPendingConfiguration = config;
701 }
702 }
703 }
704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 public final void schedulePauseActivity(IBinder token, boolean finished,
Dianne Hackborna4e102e2014-09-04 22:52:27 -0700706 boolean userLeaving, int configChanges, boolean dontReport) {
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700707 int seq = getLifecycleSeq();
708 if (DEBUG_ORDER) Slog.d(TAG, "pauseActivity " + ActivityThread.this
709 + " operation received seq: " + seq);
Jeff Brown9ef09972013-10-15 20:49:59 -0700710 sendMessage(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
712 token,
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700713 (userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),
714 configChanges,
715 seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 }
717
718 public final void scheduleStopActivity(IBinder token, boolean showWindow,
719 int configChanges) {
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700720 int seq = getLifecycleSeq();
721 if (DEBUG_ORDER) Slog.d(TAG, "stopActivity " + ActivityThread.this
722 + " operation received seq: " + seq);
723 sendMessage(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700725 token, 0, configChanges, seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 }
727
728 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700729 sendMessage(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
731 token);
732 }
733
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800734 public final void scheduleSleeping(IBinder token, boolean sleeping) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700735 sendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800736 }
737
Dianne Hackborna413dc02013-07-12 12:02:55 -0700738 public final void scheduleResumeActivity(IBinder token, int processState,
Adam Powellcfbe9be2013-11-06 14:58:58 -0800739 boolean isForward, Bundle resumeArgs) {
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700740 int seq = getLifecycleSeq();
741 if (DEBUG_ORDER) Slog.d(TAG, "resumeActivity " + ActivityThread.this
742 + " operation received seq: " + seq);
Dianne Hackborna413dc02013-07-12 12:02:55 -0700743 updateProcessState(processState, false);
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700744 sendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0, 0, seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746
747 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
748 ResultData res = new ResultData();
749 res.token = token;
750 res.results = results;
Jeff Brown9ef09972013-10-15 20:49:59 -0700751 sendMessage(H.SEND_RESULT, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 }
753
754 // we use token to identify this activity without having to send the
755 // activity itself back to the activity manager. (matters more with ipc)
Wale Ogunwale60454db2015-01-23 16:05:07 -0800756 @Override
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700757 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
Wale Ogunwale60454db2015-01-23 16:05:07 -0800758 ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
759 CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
760 int procState, Bundle state, PersistableBundle persistentState,
761 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
762 boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
Dianne Hackborna413dc02013-07-12 12:02:55 -0700763
764 updateProcessState(procState, false);
765
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700766 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767
768 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700769 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 r.intent = intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800771 r.referrer = referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700772 r.voiceInteractor = voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 r.activityInfo = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400774 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 r.state = state;
Craig Mautnera0026042014-04-23 11:45:37 -0700776 r.persistentState = persistentState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777
778 r.pendingResults = pendingResults;
779 r.pendingIntents = pendingNewIntents;
780
781 r.startsNotResumed = notResumed;
782 r.isForward = isForward;
783
Jeff Hao1b012d32014-08-20 10:35:34 -0700784 r.profilerInfo = profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700785
Wale Ogunwale60454db2015-01-23 16:05:07 -0800786 r.overrideConfig = overrideConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700787 updatePendingConfiguration(curConfig);
788
Jeff Brown9ef09972013-10-15 20:49:59 -0700789 sendMessage(H.LAUNCH_ACTIVITY, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 }
791
Wale Ogunwale60454db2015-01-23 16:05:07 -0800792 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 public final void scheduleRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800794 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Wale Ogunwale60454db2015-01-23 16:05:07 -0800795 int configChanges, boolean notResumed, Configuration config,
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700796 Configuration overrideConfig, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800797 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700798 configChanges, notResumed, config, overrideConfig, true, preserveWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800
Wale Ogunwale826c7062016-09-13 08:25:54 -0700801 public final void scheduleNewIntent(
802 List<ReferrerIntent> intents, IBinder token, boolean andPause) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 NewIntentData data = new NewIntentData();
804 data.intents = intents;
805 data.token = token;
Wale Ogunwale826c7062016-09-13 08:25:54 -0700806 data.andPause = andPause;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807
Jeff Brown9ef09972013-10-15 20:49:59 -0700808 sendMessage(H.NEW_INTENT, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 }
810
811 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
812 int configChanges) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700813 sendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 configChanges);
815 }
816
817 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400818 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700819 boolean sync, int sendingUser, int processState) {
820 updateProcessState(processState, false);
Dianne Hackborne829fef2010-10-26 17:44:01 -0700821 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700822 sync, false, mAppThread.asBinder(), sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400824 r.compatInfo = compatInfo;
Jeff Brown9ef09972013-10-15 20:49:59 -0700825 sendMessage(H.RECEIVER, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400828 public final void scheduleCreateBackupAgent(ApplicationInfo app,
829 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700830 CreateBackupAgentData d = new CreateBackupAgentData();
831 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400832 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700833 d.backupMode = backupMode;
834
Jeff Brown9ef09972013-10-15 20:49:59 -0700835 sendMessage(H.CREATE_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700836 }
837
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400838 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
839 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700840 CreateBackupAgentData d = new CreateBackupAgentData();
841 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400842 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700843
Jeff Brown9ef09972013-10-15 20:49:59 -0700844 sendMessage(H.DESTROY_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700845 }
846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 public final void scheduleCreateService(IBinder token,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700848 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
849 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 CreateServiceData s = new CreateServiceData();
851 s.token = token;
852 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400853 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854
Jeff Brown9ef09972013-10-15 20:49:59 -0700855 sendMessage(H.CREATE_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857
858 public final void scheduleBindService(IBinder token, Intent intent,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700859 boolean rebind, int processState) {
860 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 BindServiceData s = new BindServiceData();
862 s.token = token;
863 s.intent = intent;
864 s.rebind = rebind;
865
Amith Yamasani742a6712011-05-04 14:49:28 -0700866 if (DEBUG_SERVICE)
867 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
868 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
Jeff Brown9ef09972013-10-15 20:49:59 -0700869 sendMessage(H.BIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 }
871
872 public final void scheduleUnbindService(IBinder token, Intent intent) {
873 BindServiceData s = new BindServiceData();
874 s.token = token;
875 s.intent = intent;
876
Jeff Brown9ef09972013-10-15 20:49:59 -0700877 sendMessage(H.UNBIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700880 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
881 List<ServiceStartArgs> list = args.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700883 for (int i = 0; i < list.size(); i++) {
884 ServiceStartArgs ssa = list.get(i);
885 ServiceArgsData s = new ServiceArgsData();
886 s.token = token;
887 s.taskRemoved = ssa.taskRemoved;
888 s.startId = ssa.startId;
889 s.flags = ssa.flags;
890 s.args = ssa.args;
891
892 sendMessage(H.SERVICE_ARGS, s);
893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
895
896 public final void scheduleStopService(IBinder token) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700897 sendMessage(H.STOP_SERVICE, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 }
899
Jeff Hao1b012d32014-08-20 10:35:34 -0700900 public final void bindApplication(String processName, ApplicationInfo appInfo,
901 List<ProviderInfo> providers, ComponentName instrumentationName,
902 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
903 IInstrumentationWatcher instrumentationWatcher,
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800904 IUiAutomationConnection instrumentationUiConnection, int debugMode,
Pablo Ceballosa4d4e822015-10-05 10:27:52 -0700905 boolean enableBinderTracking, boolean trackAllocation,
906 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700907 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
Svet Ganov37e43272016-09-09 16:01:32 -0700908 String buildSerial) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909
910 if (services != null) {
911 // Setup the service cache in the ServiceManager
912 ServiceManager.initServiceCache(services);
913 }
914
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800915 setCoreSettings(coreSettings);
916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 AppBindData data = new AppBindData();
918 data.processName = processName;
919 data.appInfo = appInfo;
920 data.providers = providers;
921 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 data.instrumentationArgs = instrumentationArgs;
923 data.instrumentationWatcher = instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800924 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 data.debugMode = debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400926 data.enableBinderTracking = enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700927 data.trackAllocation = trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -0700928 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700929 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400931 data.compatInfo = compatInfo;
Jeff Hao1b012d32014-08-20 10:35:34 -0700932 data.initProfilerInfo = profilerInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700933 data.buildSerial = buildSerial;
Jeff Brown9ef09972013-10-15 20:49:59 -0700934 sendMessage(H.BIND_APPLICATION, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400937 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
938 SomeArgs args = SomeArgs.obtain();
939 args.arg1 = entryPoint;
940 args.arg2 = entryPointArgs;
941 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
942 }
943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 public final void scheduleExit() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700945 sendMessage(H.EXIT_APPLICATION, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 }
947
Christopher Tate5e1ab332009-09-01 20:32:49 -0700948 public final void scheduleSuicide() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700949 sendMessage(H.SUICIDE, null);
Christopher Tate5e1ab332009-09-01 20:32:49 -0700950 }
951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700953 updatePendingConfiguration(config);
Jeff Brown9ef09972013-10-15 20:49:59 -0700954 sendMessage(H.CONFIGURATION_CHANGED, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 }
956
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100957 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
958 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
959 }
960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 public void updateTimeZone() {
962 TimeZone.setDefault(null);
963 }
964
Robert Greenwalt03595d02010-11-02 14:08:23 -0700965 public void clearDnsCache() {
966 // a non-standard API to get this to libcore
967 InetAddress.clearDnsCache();
Paul Jensene401d172014-09-12 10:47:39 -0400968 // Allow libcore to perform the necessary actions as it sees fit upon a network
969 // configuration change.
970 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Robert Greenwalt03595d02010-11-02 14:08:23 -0700971 }
972
Jason Monk83520b92014-05-09 15:16:06 -0400973 public void setHttpProxy(String host, String port, String exclList, Uri pacFileUrl) {
Paul Jensen72db88e2015-03-10 10:54:12 -0400974 final ConnectivityManager cm = ConnectivityManager.from(getSystemContext());
975 final Network network = cm.getBoundNetworkForProcess();
Paul Jensene0bef712014-12-10 15:12:18 -0500976 if (network != null) {
Paul Jensen72db88e2015-03-10 10:54:12 -0400977 Proxy.setHttpProxySystemProperty(cm.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -0500978 } else {
979 Proxy.setHttpProxySystemProperty(host, port, exclList, pacFileUrl);
980 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700981 }
982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 public void processInBackground() {
984 mH.removeMessages(H.GC_WHEN_IDLE);
985 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
986 }
987
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700988 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700989 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700990 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700991 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700992 data.token = servicetoken;
993 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -0700994 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700995 } catch (IOException e) {
996 Slog.w(TAG, "dumpService failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700997 } finally {
998 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 }
1000 }
1001
1002 // This function exists to make sure all receiver dispatching is
1003 // correctly ordered, since these are one-way calls and the binder driver
1004 // applies transaction ordering per object for such calls.
1005 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001006 int resultCode, String dataStr, Bundle extras, boolean ordered,
Dianne Hackborna413dc02013-07-12 12:02:55 -07001007 boolean sticky, int sendingUser, int processState) throws RemoteException {
1008 updateProcessState(processState, false);
Dianne Hackborn20e80982012-08-31 19:00:44 -07001009 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
1010 sticky, sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 }
Bob Leee5408332009-09-04 18:31:17 -07001012
Wale Ogunwalec2607b42015-02-07 16:16:59 -08001013 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 public void scheduleLowMemory() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001015 sendMessage(H.LOW_MEMORY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 }
1017
Wale Ogunwale60454db2015-01-23 16:05:07 -08001018 @Override
Wale Ogunwalec2607b42015-02-07 16:16:59 -08001019 public void scheduleActivityConfigurationChanged(
Andrii Kulianb047b8b2017-02-08 18:38:26 -08001020 IBinder token, Configuration overrideConfig) {
Wale Ogunwalec2607b42015-02-07 16:16:59 -08001021 sendMessage(H.ACTIVITY_CONFIGURATION_CHANGED,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08001022 new ActivityConfigChangeData(token, overrideConfig));
1023 }
1024
1025 @Override
1026 public void scheduleActivityMovedToDisplay(IBinder token, int displayId,
1027 Configuration overrideConfig) {
1028 sendMessage(H.ACTIVITY_MOVED_TO_DISPLAY,
1029 new ActivityConfigChangeData(token, overrideConfig), displayId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
1031
Wale Ogunwalec2607b42015-02-07 16:16:59 -08001032 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -07001033 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
1034 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001035 }
1036
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001037 @Override
Christopher Ferris8d652f82017-04-11 16:29:18 -07001038 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
1039 ParcelFileDescriptor fd) {
Andy McFadden824c5102010-07-09 16:26:57 -07001040 DumpHeapData dhd = new DumpHeapData();
Christopher Ferris8d652f82017-04-11 16:29:18 -07001041 dhd.managed = managed;
1042 dhd.mallocInfo = mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001043 dhd.runGc = runGc;
Andy McFadden824c5102010-07-09 16:26:57 -07001044 dhd.path = path;
1045 dhd.fd = fd;
Christopher Ferris8d652f82017-04-11 16:29:18 -07001046 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
Andy McFadden824c5102010-07-09 16:26:57 -07001047 }
1048
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001049 public void attachAgent(String agent) {
1050 sendMessage(H.ATTACH_AGENT, agent);
1051 }
1052
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001053 public void setSchedulingGroup(int group) {
1054 // Note: do this immediately, since going into the foreground
1055 // should happen regardless of what pending work we have to do
1056 // and the activity manager will wait for us to report back that
1057 // we are done before sending us to the background.
1058 try {
1059 Process.setProcessGroup(Process.myPid(), group);
1060 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001061 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001062 }
1063 }
Bob Leee5408332009-09-04 18:31:17 -07001064
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001065 public void dispatchPackageBroadcast(int cmd, String[] packages) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001066 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001067 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001068
1069 public void scheduleCrash(String msg) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001070 sendMessage(H.SCHEDULE_CRASH, msg);
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001071 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07001072
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001073 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
Dianne Hackborn30d71892010-12-11 10:37:55 -08001074 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001075 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001076 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001077 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001078 data.token = activitytoken;
1079 data.prefix = prefix;
1080 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001081 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001082 } catch (IOException e) {
1083 Slog.w(TAG, "dumpActivity failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001084 } finally {
1085 IoUtils.closeQuietly(pfd);
Dianne Hackborn625ac272010-09-17 18:29:22 -07001086 }
1087 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07001088
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001089 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
Marco Nelissen18cb2872011-11-15 11:19:53 -08001090 String[] args) {
1091 DumpComponentInfo data = new DumpComponentInfo();
1092 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001093 data.fd = pfd.dup();
Marco Nelissen18cb2872011-11-15 11:19:53 -08001094 data.token = providertoken;
1095 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001096 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001097 } catch (IOException e) {
1098 Slog.w(TAG, "dumpProvider failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001099 } finally {
1100 IoUtils.closeQuietly(pfd);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001101 }
1102 }
1103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001105 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001106 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1107 boolean dumpUnreachable, String[] args) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001108 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
Dianne Hackborn8c841092013-06-24 13:46:13 -07001109 PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001110 try {
Colin Crossc4fb5f92016-02-02 16:51:15 -08001111 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001112 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -07001113 pw.flush();
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001114 IoUtils.closeQuietly(pfd);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001115 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001116 }
1117
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001118 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001119 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 long nativeMax = Debug.getNativeHeapSize() / 1024;
1121 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1122 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 Runtime runtime = Runtime.getRuntime();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001125 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 long dalvikMax = runtime.totalMemory() / 1024;
1127 long dalvikFree = runtime.freeMemory() / 1024;
1128 long dalvikAllocated = dalvikMax - dalvikFree;
Richard Uhler2c036192016-09-14 09:48:31 +01001129
1130 Class[] classesToCount = new Class[] {
1131 ContextImpl.class,
1132 Activity.class,
1133 WebView.class,
1134 OpenSSLSocketImpl.class
1135 };
1136 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1137 long appContextInstanceCount = instanceCounts[0];
1138 long activityInstanceCount = instanceCounts[1];
1139 long webviewInstanceCount = instanceCounts[2];
1140 long openSslSocketCount = instanceCounts[3];
1141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -07001143 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 int globalAssetCount = AssetManager.getGlobalAssetCount();
1145 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1146 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1147 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1148 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001149 long parcelSize = Parcel.getGlobalAllocSize();
1150 long parcelCount = Parcel.getGlobalAllocCount();
Vasu Noric3849202010-03-09 10:47:25 -08001151 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -07001152
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07001153 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1154 Process.myPid(),
Dianne Hackborne77187d2013-10-25 16:32:41 -07001155 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1156 nativeMax, nativeAllocated, nativeFree,
1157 dalvikMax, dalvikAllocated, dalvikFree);
1158
Dianne Hackbornb437e092011-08-05 17:50:29 -07001159 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 // NOTE: if you change anything significant below, also consider changing
1161 // ACTIVITY_THREAD_CHECKIN_VERSION.
Anwar Ghuloum3c615062013-05-13 14:18:02 -07001162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 // Object counts
1164 pw.print(viewInstanceCount); pw.print(',');
1165 pw.print(viewRootInstanceCount); pw.print(',');
1166 pw.print(appContextInstanceCount); pw.print(',');
1167 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 pw.print(globalAssetCount); pw.print(',');
1170 pw.print(globalAssetManagerCount); pw.print(',');
1171 pw.print(binderLocalObjectCount); pw.print(',');
1172 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 pw.print(binderDeathObjectCount); pw.print(',');
1175 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 // SQL
Vasu Noric3849202010-03-09 10:47:25 -08001178 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -08001179 pw.print(stats.memoryUsed / 1024); pw.print(',');
1180 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -07001181 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001182 for (int i = 0; i < stats.dbStats.size(); i++) {
1183 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -07001184 pw.print(','); pw.print(dbStats.dbName);
1185 pw.print(','); pw.print(dbStats.pageSize);
1186 pw.print(','); pw.print(dbStats.dbSize);
1187 pw.print(','); pw.print(dbStats.lookaside);
1188 pw.print(','); pw.print(dbStats.cache);
1189 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -08001190 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07001191 pw.println();
Bob Leee5408332009-09-04 18:31:17 -07001192
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001193 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 }
Bob Leee5408332009-09-04 18:31:17 -07001195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 pw.println(" ");
1197 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001198 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 viewRootInstanceCount);
1200
1201 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1202 "Activities:", activityInstanceCount);
1203
1204 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1205 "AssetManagers:", globalAssetManagerCount);
1206
1207 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1208 "Proxy Binders:", binderProxyObjectCount);
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001209 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1210 "Parcel count:", parcelCount);
1211 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1212 "OpenSSL Sockets:", openSslSocketCount);
Richard Uhler2c036192016-09-14 09:48:31 +01001213 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
Bob Leee5408332009-09-04 18:31:17 -07001214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 // SQLite mem info
1216 pw.println(" ");
1217 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001218 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1219 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1220 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001221 pw.println(" ");
1222 int N = stats.dbStats.size();
1223 if (N > 0) {
1224 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -07001225 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
1226 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001227 for (int i = 0; i < N; i++) {
1228 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001229 printRow(pw, DB_INFO_FORMAT,
1230 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1231 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1232 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1233 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001234 }
1235 }
Bob Leee5408332009-09-04 18:31:17 -07001236
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001237 // Asset details.
1238 String assetAlloc = AssetManager.getAssetAllocations();
1239 if (assetAlloc != null) {
1240 pw.println(" ");
1241 pw.println(" Asset Allocations");
1242 pw.print(assetAlloc);
1243 }
Colin Crossc4fb5f92016-02-02 16:51:15 -08001244
1245 // Unreachable native memory
1246 if (dumpUnreachable) {
1247 boolean showContents = ((mBoundApplication != null)
1248 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1249 || android.os.Build.IS_DEBUGGABLE;
1250 pw.println(" ");
1251 pw.println(" Unreachable memory");
1252 pw.print(Debug.getUnreachableMemory(100, showContents));
1253 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001254 }
1255
1256 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001257 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
Chris Craikfc294242016-12-13 18:10:46 -08001258 nDumpGraphicsInfo(pfd.getFileDescriptor());
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001259 WindowManagerGlobal.getInstance().dumpGfxInfo(pfd.getFileDescriptor(), args);
1260 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
1262
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001263 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args) {
1264 PrintWriter pw = new FastPrintWriter(
1265 new FileOutputStream(pfd.getFileDescriptor()));
Jeff Brown6754ba22011-12-14 20:20:01 -08001266 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1267 SQLiteDebug.dump(printer, args);
1268 pw.flush();
1269 }
1270
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001271 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001272 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001273 if (mSystemThread) {
Felipe Leme29de4922016-06-07 16:14:07 -07001274 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1275 // be consumed. But it must duplicate the file descriptor first, since caller might
1276 // be closing it.
1277 final ParcelFileDescriptor dup;
1278 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001279 dup = pfd.dup();
Felipe Leme29de4922016-06-07 16:14:07 -07001280 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001281 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
Felipe Leme29de4922016-06-07 16:14:07 -07001282 return;
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001283 } finally {
1284 IoUtils.closeQuietly(pfd);
Felipe Leme29de4922016-06-07 16:14:07 -07001285 }
1286
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001287 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1288 @Override
1289 public void run() {
Felipe Lemec74972f2016-06-08 09:12:37 -07001290 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001291 dumpDatabaseInfo(dup, args);
Felipe Lemec74972f2016-06-08 09:12:37 -07001292 } finally {
1293 IoUtils.closeQuietly(dup);
1294 }
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001295 }
1296 });
1297 } else {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001298 dumpDatabaseInfo(pfd, args);
1299 IoUtils.closeQuietly(pfd);
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001300 }
1301 }
1302
1303 @Override
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001304 public void unstableProviderDied(IBinder provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001305 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001306 }
1307
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001308 @Override
Adam Skorydfc7fd72013-08-05 19:23:41 -07001309 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
Svet Ganovfd31f852017-04-26 15:54:27 -07001310 int requestType, int sessionId, int flags) {
Adam Skorydfc7fd72013-08-05 19:23:41 -07001311 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001312 cmd.activityToken = activityToken;
1313 cmd.requestToken = requestToken;
1314 cmd.requestType = requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -07001315 cmd.sessionId = sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -07001316 cmd.flags = flags;
Jeff Brown9ef09972013-10-15 20:49:59 -07001317 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001318 }
1319
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001320 public void setCoreSettings(Bundle coreSettings) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001321 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001322 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001323
1324 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1325 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1326 ucd.pkg = pkg;
1327 ucd.info = info;
Jeff Brown9ef09972013-10-15 20:49:59 -07001328 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001329 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001330
1331 public void scheduleTrimMemory(int level) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001332 sendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001333 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001334
Craig Mautner5eda9b32013-07-02 11:58:16 -07001335 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001336 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001337 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001338
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001339 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
Craig Mautnereb8abf72014-07-02 15:04:09 -07001340 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001341 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
Craig Mautnereb8abf72014-07-02 15:04:09 -07001342 }
1343
Dianne Hackborna413dc02013-07-12 12:02:55 -07001344 public void setProcessState(int state) {
1345 updateProcessState(state, true);
1346 }
1347
1348 public void updateProcessState(int processState, boolean fromIpc) {
1349 synchronized (this) {
1350 if (mLastProcessState != processState) {
1351 mLastProcessState = processState;
Mathieu Chartier1e370902013-07-18 10:58:01 -07001352 // Update Dalvik state based on ActivityManager.PROCESS_STATE_* constants.
1353 final int DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
1354 final int DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
1355 int dalvikProcessState = DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE;
1356 // TODO: Tune this since things like gmail sync are important background but not jank perceptible.
1357 if (processState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
1358 dalvikProcessState = DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE;
1359 }
1360 VMRuntime.getRuntime().updateProcessState(dalvikProcessState);
Dianne Hackborna413dc02013-07-12 12:02:55 -07001361 if (false) {
1362 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
1363 + (fromIpc ? " (from ipc": ""));
1364 }
1365 }
1366 }
1367 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001368
Sudheer Shanka84a48952017-03-08 18:19:01 -08001369 /**
1370 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1371 * the main thread that it needs to wait for the network rules to get updated before
1372 * launching an activity.
1373 */
1374 @Override
1375 public void setNetworkBlockSeq(long procStateSeq) {
1376 synchronized (mNetworkPolicyLock) {
1377 mNetworkBlockSeq = procStateSeq;
1378 }
1379 }
1380
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001381 @Override
1382 public void scheduleInstallProvider(ProviderInfo provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001383 sendMessage(H.INSTALL_PROVIDER, provider);
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001384 }
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001385
1386 @Override
Neil Fullerb7146fe2016-11-15 16:52:15 +00001387 public final void updateTimePrefs(int timeFormatPreference) {
1388 final Boolean timeFormatPreferenceBool;
1389 // For convenience we are using the Intent extra values.
1390 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1391 timeFormatPreferenceBool = Boolean.FALSE;
1392 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1393 timeFormatPreferenceBool = Boolean.TRUE;
1394 } else {
1395 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1396 // (or unknown).
1397 timeFormatPreferenceBool = null;
1398 }
1399 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001400 }
Craig Mautneree2e45a2014-06-27 12:10:03 -07001401
1402 @Override
Craig Mautner8746a472014-07-24 15:12:54 -07001403 public void scheduleEnterAnimationComplete(IBinder token) {
1404 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1405 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001406
1407 @Override
1408 public void notifyCleartextNetwork(byte[] firstPacket) {
1409 if (StrictMode.vmCleartextNetworkEnabled()) {
1410 StrictMode.onCleartextNetworkDetected(firstPacket);
1411 }
1412 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001413
1414 @Override
1415 public void startBinderTracking() {
1416 sendMessage(H.START_BINDER_TRACKING, null);
1417 }
1418
1419 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001420 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001421 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001422 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001423 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001424 } finally {
1425 IoUtils.closeQuietly(pfd);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001426 }
1427 }
Wale Ogunwale5f986092015-12-04 15:35:38 -08001428
1429 @Override
Winson Chung5af42fc2017-03-24 17:11:33 -07001430 public void scheduleMultiWindowModeChanged(IBinder token, boolean isInMultiWindowMode,
1431 Configuration overrideConfig) throws RemoteException {
1432 SomeArgs args = SomeArgs.obtain();
1433 args.arg1 = token;
1434 args.arg2 = overrideConfig;
1435 args.argi1 = isInMultiWindowMode ? 1 : 0;
1436 sendMessage(H.MULTI_WINDOW_MODE_CHANGED, args);
Wale Ogunwale5f986092015-12-04 15:35:38 -08001437 }
1438
1439 @Override
Winson Chung5af42fc2017-03-24 17:11:33 -07001440 public void schedulePictureInPictureModeChanged(IBinder token, boolean isInPipMode,
1441 Configuration overrideConfig) throws RemoteException {
1442 SomeArgs args = SomeArgs.obtain();
1443 args.arg1 = token;
1444 args.arg2 = overrideConfig;
1445 args.argi1 = isInPipMode ? 1 : 0;
1446 sendMessage(H.PICTURE_IN_PICTURE_MODE_CHANGED, args);
Wale Ogunwale5f986092015-12-04 15:35:38 -08001447 }
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001448
1449 @Override
1450 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1451 IVoiceInteractor voiceInteractor) throws RemoteException {
1452 SomeArgs args = SomeArgs.obtain();
1453 args.arg1 = token;
1454 args.arg2 = voiceInteractor;
1455 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1456 }
Chad Brubakerc72875b2016-04-27 16:35:11 -07001457
1458 @Override
1459 public void handleTrustStorageUpdate() {
1460 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 }
1463
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001464 private int getLifecycleSeq() {
1465 synchronized (mResourcesManager) {
1466 return mLifecycleSeq++;
1467 }
1468 }
1469
Romain Guy65b345f2011-07-27 18:51:50 -07001470 private class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 public static final int LAUNCH_ACTIVITY = 100;
1472 public static final int PAUSE_ACTIVITY = 101;
1473 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1474 public static final int STOP_ACTIVITY_SHOW = 103;
1475 public static final int STOP_ACTIVITY_HIDE = 104;
1476 public static final int SHOW_WINDOW = 105;
1477 public static final int HIDE_WINDOW = 106;
1478 public static final int RESUME_ACTIVITY = 107;
1479 public static final int SEND_RESULT = 108;
Brian Carlstromed7e0072011-03-24 13:27:57 -07001480 public static final int DESTROY_ACTIVITY = 109;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 public static final int BIND_APPLICATION = 110;
1482 public static final int EXIT_APPLICATION = 111;
1483 public static final int NEW_INTENT = 112;
1484 public static final int RECEIVER = 113;
1485 public static final int CREATE_SERVICE = 114;
1486 public static final int SERVICE_ARGS = 115;
1487 public static final int STOP_SERVICE = 116;
Dianne Hackborn09233282014-04-30 11:33:59 -07001488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 public static final int CONFIGURATION_CHANGED = 118;
1490 public static final int CLEAN_UP_CONTEXT = 119;
1491 public static final int GC_WHEN_IDLE = 120;
1492 public static final int BIND_SERVICE = 121;
1493 public static final int UNBIND_SERVICE = 122;
1494 public static final int DUMP_SERVICE = 123;
1495 public static final int LOW_MEMORY = 124;
1496 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1497 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001498 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001499 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001500 public static final int DESTROY_BACKUP_AGENT = 129;
1501 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001502 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001503 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001504 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001505 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001506 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001507 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001508 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001509 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001510 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001511 public static final int TRIM_MEMORY = 140;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001512 public static final int DUMP_PROVIDER = 141;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001513 public static final int UNSTABLE_PROVIDER_DIED = 142;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001514 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001515 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001516 public static final int INSTALL_PROVIDER = 145;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001517 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
Craig Mautner8746a472014-07-24 15:12:54 -07001518 public static final int ENTER_ANIMATION_COMPLETE = 149;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001519 public static final int START_BINDER_TRACKING = 150;
1520 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
Andrii Kulian933076d2016-03-29 17:04:42 -07001521 public static final int MULTI_WINDOW_MODE_CHANGED = 152;
1522 public static final int PICTURE_IN_PICTURE_MODE_CHANGED = 153;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001523 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001524 public static final int ATTACH_AGENT = 155;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001525 public static final int APPLICATION_INFO_CHANGED = 156;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08001526 public static final int ACTIVITY_MOVED_TO_DISPLAY = 157;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001527 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001530 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 switch (code) {
1532 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1533 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1534 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1535 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1536 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1537 case SHOW_WINDOW: return "SHOW_WINDOW";
1538 case HIDE_WINDOW: return "HIDE_WINDOW";
1539 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1540 case SEND_RESULT: return "SEND_RESULT";
1541 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1542 case BIND_APPLICATION: return "BIND_APPLICATION";
1543 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1544 case NEW_INTENT: return "NEW_INTENT";
1545 case RECEIVER: return "RECEIVER";
1546 case CREATE_SERVICE: return "CREATE_SERVICE";
1547 case SERVICE_ARGS: return "SERVICE_ARGS";
1548 case STOP_SERVICE: return "STOP_SERVICE";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1550 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1551 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1552 case BIND_SERVICE: return "BIND_SERVICE";
1553 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1554 case DUMP_SERVICE: return "DUMP_SERVICE";
1555 case LOW_MEMORY: return "LOW_MEMORY";
1556 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
Andrii Kulianb047b8b2017-02-08 18:38:26 -08001557 case ACTIVITY_MOVED_TO_DISPLAY: return "ACTIVITY_MOVED_TO_DISPLAY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001559 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001560 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1561 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001562 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001563 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001564 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001565 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001566 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001567 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001568 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001569 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001570 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001571 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001572 case TRIM_MEMORY: return "TRIM_MEMORY";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001573 case DUMP_PROVIDER: return "DUMP_PROVIDER";
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001574 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
Adam Skorydfc7fd72013-08-05 19:23:41 -07001575 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
Craig Mautner5eda9b32013-07-02 11:58:16 -07001576 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001577 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
Craig Mautnereb8abf72014-07-02 15:04:09 -07001578 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
Craig Mautner8746a472014-07-24 15:12:54 -07001579 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
Andrii Kulian933076d2016-03-29 17:04:42 -07001580 case MULTI_WINDOW_MODE_CHANGED: return "MULTI_WINDOW_MODE_CHANGED";
1581 case PICTURE_IN_PICTURE_MODE_CHANGED: return "PICTURE_IN_PICTURE_MODE_CHANGED";
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001582 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001583 case ATTACH_AGENT: return "ATTACH_AGENT";
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001584 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001585 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001588 return Integer.toString(code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590 public void handleMessage(Message msg) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001591 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 switch (msg.what) {
1593 case LAUNCH_ACTIVITY: {
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001594 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
Adam Powellcfbe9be2013-11-06 14:58:58 -08001595 final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596
1597 r.packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001598 r.activityInfo.applicationInfo, r.compatInfo);
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08001599 handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001600 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 } break;
1602 case RELAUNCH_ACTIVITY: {
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001603 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001604 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001605 handleRelaunchActivity(r);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001606 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 } break;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001608 case PAUSE_ACTIVITY: {
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001609 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001610 SomeArgs args = (SomeArgs) msg.obj;
1611 handlePauseActivity((IBinder) args.arg1, false,
1612 (args.argi1 & USER_LEAVING) != 0, args.argi2,
1613 (args.argi1 & DONT_REPORT) != 0, args.argi3);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001614 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001615 } break;
1616 case PAUSE_ACTIVITY_FINISHING: {
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001617 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001618 SomeArgs args = (SomeArgs) msg.obj;
1619 handlePauseActivity((IBinder) args.arg1, true, (args.argi1 & USER_LEAVING) != 0,
1620 args.argi2, (args.argi1 & DONT_REPORT) != 0, args.argi3);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001621 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001622 } break;
1623 case STOP_ACTIVITY_SHOW: {
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001624 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001625 SomeArgs args = (SomeArgs) msg.obj;
1626 handleStopActivity((IBinder) args.arg1, true, args.argi2, args.argi3);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001627 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001628 } break;
1629 case STOP_ACTIVITY_HIDE: {
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001630 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001631 SomeArgs args = (SomeArgs) msg.obj;
1632 handleStopActivity((IBinder) args.arg1, false, args.argi2, args.argi3);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001633 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001634 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 case SHOW_WINDOW:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001636 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityShowWindow");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 handleWindowVisibility((IBinder)msg.obj, true);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001638 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 break;
1640 case HIDE_WINDOW:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001641 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityHideWindow");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 handleWindowVisibility((IBinder)msg.obj, false);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001643 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 break;
1645 case RESUME_ACTIVITY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001646 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001647 SomeArgs args = (SomeArgs) msg.obj;
1648 handleResumeActivity((IBinder) args.arg1, true, args.argi1 != 0, true,
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08001649 args.argi3, "RESUME_ACTIVITY");
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 SEND_RESULT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001653 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDeliverResult");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 handleSendResult((ResultData)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 DESTROY_ACTIVITY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001658 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDestroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1660 msg.arg2, false);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001661 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 break;
1663 case BIND_APPLICATION:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001664 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 AppBindData data = (AppBindData)msg.obj;
1666 handleBindApplication(data);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001667 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 break;
1669 case EXIT_APPLICATION:
1670 if (mInitialApplication != null) {
1671 mInitialApplication.onTerminate();
1672 }
1673 Looper.myLooper().quit();
1674 break;
1675 case NEW_INTENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001676 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityNewIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 handleNewIntent((NewIntentData)msg.obj);
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;
1680 case RECEIVER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001681 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 handleReceiver((ReceiverData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001683 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 break;
1685 case CREATE_SERVICE:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001686 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 handleCreateService((CreateServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001688 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 break;
1690 case BIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001691 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 handleBindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001693 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 break;
1695 case UNBIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001696 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 handleUnbindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001698 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 break;
1700 case SERVICE_ARGS:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001701 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceStart: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 handleServiceArgs((ServiceArgsData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001703 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 break;
1705 case STOP_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001706 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 handleStopService((IBinder)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001708 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 case CONFIGURATION_CHANGED:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001711 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001712 mCurDefaultDisplayDpi = ((Configuration)msg.obj).densityDpi;
Chong Zhang4951f9d2016-06-23 13:15:08 -07001713 mUpdatingSystemConfig = true;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001714 try {
1715 handleConfigurationChanged((Configuration) msg.obj, null);
1716 } finally {
1717 mUpdatingSystemConfig = false;
1718 }
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001719 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 break;
1721 case CLEAN_UP_CONTEXT:
1722 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1723 cci.context.performFinalCleanup(cci.who, cci.what);
1724 break;
1725 case GC_WHEN_IDLE:
1726 scheduleGcIdler();
1727 break;
1728 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001729 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 break;
1731 case LOW_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001732 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 handleLowMemory();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001734 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 break;
1736 case ACTIVITY_CONFIGURATION_CHANGED:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001737 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityConfigChanged");
Filip Gruszczynskica664812015-12-04 12:43:36 -08001738 handleActivityConfigurationChanged((ActivityConfigChangeData) msg.obj,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08001739 INVALID_DISPLAY);
1740 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1741 break;
1742 case ACTIVITY_MOVED_TO_DISPLAY:
1743 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityMovedToDisplay");
1744 handleActivityConfigurationChanged((ActivityConfigChangeData) msg.obj,
1745 msg.arg1 /* displayId */);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001746 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001748 case PROFILER_CONTROL:
Jeff Hao1b012d32014-08-20 10:35:34 -07001749 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001750 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001751 case CREATE_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001752 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001753 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001754 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001755 break;
1756 case DESTROY_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001757 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001758 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001759 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001760 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001761 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001762 Process.killProcess(Process.myPid());
1763 break;
1764 case REMOVE_PROVIDER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001765 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001766 completeRemoveProvider((ProviderRefCount)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001767 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001768 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001769 case ENABLE_JIT:
1770 ensureJitEnabled();
1771 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001772 case DISPATCH_PACKAGE_BROADCAST:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001773 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001774 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001775 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001776 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001777 case SCHEDULE_CRASH:
1778 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001779 case DUMP_HEAP:
Christopher Ferris8d652f82017-04-11 16:29:18 -07001780 handleDumpHeap((DumpHeapData) msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001781 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001782 case DUMP_ACTIVITY:
1783 handleDumpActivity((DumpComponentInfo)msg.obj);
1784 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001785 case DUMP_PROVIDER:
1786 handleDumpProvider((DumpComponentInfo)msg.obj);
1787 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001788 case SLEEPING:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001789 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001790 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001791 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001792 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001793 case SET_CORE_SETTINGS:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001794 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001795 handleSetCoreSettings((Bundle) msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001796 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001797 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001798 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1799 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001800 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001801 case TRIM_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001802 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001803 handleTrimMemory(msg.arg1);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001804 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001805 break;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001806 case UNSTABLE_PROVIDER_DIED:
1807 handleUnstableProviderDied((IBinder)msg.obj, false);
1808 break;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001809 case REQUEST_ASSIST_CONTEXT_EXTRAS:
1810 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001811 break;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001812 case TRANSLUCENT_CONVERSION_COMPLETE:
1813 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
1814 break;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001815 case INSTALL_PROVIDER:
1816 handleInstallProvider((ProviderInfo) msg.obj);
1817 break;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001818 case ON_NEW_ACTIVITY_OPTIONS:
1819 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
1820 onNewActivityOptions(pair.first, pair.second);
Dake Gu7ef70b02014-07-08 18:37:12 -07001821 break;
Craig Mautner8746a472014-07-24 15:12:54 -07001822 case ENTER_ANIMATION_COMPLETE:
1823 handleEnterAnimationComplete((IBinder) msg.obj);
1824 break;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001825 case START_BINDER_TRACKING:
1826 handleStartBinderTracking();
1827 break;
1828 case STOP_BINDER_TRACKING_AND_DUMP:
1829 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
1830 break;
Andrii Kulian933076d2016-03-29 17:04:42 -07001831 case MULTI_WINDOW_MODE_CHANGED:
Winson Chung5af42fc2017-03-24 17:11:33 -07001832 handleMultiWindowModeChanged((IBinder) ((SomeArgs) msg.obj).arg1,
1833 ((SomeArgs) msg.obj).argi1 == 1,
1834 (Configuration) ((SomeArgs) msg.obj).arg2);
Wale Ogunwale5f986092015-12-04 15:35:38 -08001835 break;
Andrii Kulian933076d2016-03-29 17:04:42 -07001836 case PICTURE_IN_PICTURE_MODE_CHANGED:
Winson Chung5af42fc2017-03-24 17:11:33 -07001837 handlePictureInPictureModeChanged((IBinder) ((SomeArgs) msg.obj).arg1,
1838 ((SomeArgs) msg.obj).argi1 == 1,
1839 (Configuration) ((SomeArgs) msg.obj).arg2);
Wale Ogunwale5f986092015-12-04 15:35:38 -08001840 break;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001841 case LOCAL_VOICE_INTERACTION_STARTED:
1842 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
1843 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
Amith Yamasani61019112017-01-10 15:05:00 -08001844 break;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001845 case ATTACH_AGENT:
1846 handleAttachAgent((String) msg.obj);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001847 break;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001848 case APPLICATION_INFO_CHANGED:
1849 mUpdatingSystemConfig = true;
1850 try {
1851 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
1852 } finally {
1853 mUpdatingSystemConfig = false;
1854 }
1855 break;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001856 case RUN_ISOLATED_ENTRY_POINT:
1857 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
1858 (String[]) ((SomeArgs) msg.obj).arg2);
1859 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001861 Object obj = msg.obj;
1862 if (obj instanceof SomeArgs) {
1863 ((SomeArgs) obj).recycle();
1864 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001865 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
1867 }
1868
Romain Guy65b345f2011-07-27 18:51:50 -07001869 private class Idler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001870 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001872 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001873 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001874 if (mBoundApplication != null && mProfiler.profileFd != null
1875 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001876 stopProfiling = true;
1877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 if (a != null) {
1879 mNewActivities = null;
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001880 IActivityManager am = ActivityManager.getService();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001881 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001883 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 TAG, "Reporting idle of " + a +
1885 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001886 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 if (a.activity != null && !a.activity.mFinished) {
1888 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001889 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001890 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001892 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894 }
1895 prev = a;
1896 a = a.nextIdle;
1897 prev.nextIdle = null;
1898 } while (a != null);
1899 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001900 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001901 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001902 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001903 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 return false;
1905 }
1906 }
1907
1908 final class GcIdler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001909 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 public final boolean queueIdle() {
1911 doGcIfNeeded();
1912 return false;
1913 }
1914 }
1915
Romain Guy65b345f2011-07-27 18:51:50 -07001916 public static ActivityThread currentActivityThread() {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08001917 return sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919
Wale Ogunwale9a6ef1e2015-06-02 13:41:00 -07001920 public static boolean isSystem() {
1921 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
1922 }
1923
Svetoslavfbf0eca2015-05-01 16:52:41 -07001924 public static String currentOpPackageName() {
1925 ActivityThread am = currentActivityThread();
1926 return (am != null && am.getApplication() != null)
1927 ? am.getApplication().getOpPackageName() : null;
1928 }
1929
Romain Guy65b345f2011-07-27 18:51:50 -07001930 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001931 ActivityThread am = currentActivityThread();
1932 return (am != null && am.mBoundApplication != null)
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07001933 ? am.mBoundApplication.appInfo.packageName : null;
1934 }
1935
1936 public static String currentProcessName() {
1937 ActivityThread am = currentActivityThread();
1938 return (am != null && am.mBoundApplication != null)
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001939 ? am.mBoundApplication.processName : null;
1940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941
Romain Guy65b345f2011-07-27 18:51:50 -07001942 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001943 ActivityThread am = currentActivityThread();
1944 return am != null ? am.mInitialApplication : null;
1945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001947 public static IPackageManager getPackageManager() {
1948 if (sPackageManager != null) {
1949 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1950 return sPackageManager;
1951 }
1952 IBinder b = ServiceManager.getService("package");
1953 //Slog.v("PackageManager", "default service binder = " + b);
1954 sPackageManager = IPackageManager.Stub.asInterface(b);
1955 //Slog.v("PackageManager", "default service = " + sPackageManager);
1956 return sPackageManager;
1957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958
Romain Guy65b345f2011-07-27 18:51:50 -07001959 private Configuration mMainThreadConfig = new Configuration();
Amith Yamasani4f128e42016-05-10 11:44:12 -07001960
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001961 Configuration applyConfigCompatMainThread(int displayDensity, Configuration config,
1962 CompatibilityInfo compat) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001963 if (config == null) {
1964 return null;
1965 }
Craig Mautner48d0d182013-06-11 07:53:06 -07001966 if (!compat.supportsScreen()) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001967 mMainThreadConfig.setTo(config);
1968 config = mMainThreadConfig;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001969 compat.applyToConfiguration(displayDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001970 }
1971 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001974 /**
Todd Kennedy39bfee52016-02-24 10:28:21 -08001975 * Creates the top level resources for the given package. Will return an existing
1976 * Resources if one has already been created.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001977 */
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07001978 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
Adam Lesinski082614c2016-03-04 14:33:47 -08001979 String[] libDirs, int displayId, LoadedApk pkgInfo) {
1980 return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,
1981 displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader());
Todd Kennedy39bfee52016-02-24 10:28:21 -08001982 }
1983
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001984 final Handler getHandler() {
1985 return mH;
1986 }
1987
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001988 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1989 int flags) {
Amith Yamasani98edc952012-09-25 14:09:27 -07001990 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
1991 }
1992
1993 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1994 int flags, int userId) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001995 final boolean differentUser = (UserHandle.myUserId() != userId);
Craig Mautner88c05892013-06-28 09:47:45 -07001996 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001997 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001998 if (differentUser) {
1999 // Caching not supported across users
2000 ref = null;
2001 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 ref = mPackages.get(packageName);
2003 } else {
2004 ref = mResourcePackages.get(packageName);
2005 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002006
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002007 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002008 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07002009 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
2010 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 if (packageInfo != null && (packageInfo.mResources == null
2012 || packageInfo.mResources.getAssets().isUpToDate())) {
2013 if (packageInfo.isSecurityViolation()
2014 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2015 throw new SecurityException(
2016 "Requesting code from " + packageName
2017 + " to be run in process "
2018 + mBoundApplication.processName
2019 + "/" + mBoundApplication.appInfo.uid);
2020 }
2021 return packageInfo;
2022 }
2023 }
2024
2025 ApplicationInfo ai = null;
2026 try {
2027 ai = getPackageManager().getApplicationInfo(packageName,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002028 PackageManager.GET_SHARED_LIBRARY_FILES
2029 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2030 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002032 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 }
2034
2035 if (ai != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002036 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 }
2038
2039 return null;
2040 }
2041
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002042 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
2043 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2045 boolean securityViolation = includeCode && ai.uid != 0
2046 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002047 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
Amith Yamasani742a6712011-05-04 14:49:28 -07002048 : true);
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002049 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2051 |Context.CONTEXT_IGNORE_SECURITY))
2052 == Context.CONTEXT_INCLUDE_CODE) {
2053 if (securityViolation) {
2054 String msg = "Requesting code from " + ai.packageName
2055 + " (with uid " + ai.uid + ")";
2056 if (mBoundApplication != null) {
2057 msg = msg + " to be run in process "
2058 + mBoundApplication.processName + " (with uid "
2059 + mBoundApplication.appInfo.uid + ")";
2060 }
2061 throw new SecurityException(msg);
2062 }
2063 }
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002064 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
2065 registerPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
2067
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002068 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
2069 CompatibilityInfo compatInfo) {
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002070 return getPackageInfo(ai, compatInfo, null, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002073 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
Craig Mautner88c05892013-06-28 09:47:45 -07002074 synchronized (mResourcesManager) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002075 WeakReference<LoadedApk> ref;
2076 if (includeCode) {
2077 ref = mPackages.get(packageName);
2078 } else {
2079 ref = mResourcePackages.get(packageName);
2080 }
2081 return ref != null ? ref.get() : null;
2082 }
2083 }
2084
Romain Guy65b345f2011-07-27 18:51:50 -07002085 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002086 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2087 boolean registerPackage) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002088 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
Craig Mautner88c05892013-06-28 09:47:45 -07002089 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002090 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002091 if (differentUser) {
2092 // Caching not supported across users
2093 ref = null;
2094 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 ref = mPackages.get(aInfo.packageName);
2096 } else {
2097 ref = mResourcePackages.get(aInfo.packageName);
2098 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002099
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002100 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 if (packageInfo == null || (packageInfo.mResources != null
2102 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002103 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 : "Loading resource-only package ") + aInfo.packageName
2105 + " (in " + (mBoundApplication != null
2106 ? mBoundApplication.processName : null)
2107 + ")");
2108 packageInfo =
Jeff Browndefd4a62014-03-10 21:24:37 -07002109 new LoadedApk(this, aInfo, compatInfo, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 securityViolation, includeCode &&
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002111 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
Narayan Kamathcb383182014-10-29 17:56:42 +00002112
2113 if (mSystemThread && "android".equals(aInfo.packageName)) {
2114 packageInfo.installSystemApplicationInfo(aInfo,
2115 getSystemContext().mPackageInfo.getClassLoader());
2116 }
2117
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002118 if (differentUser) {
2119 // Caching not supported across users
2120 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002122 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 } else {
2124 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002125 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 }
2127 }
2128 return packageInfo;
2129 }
2130 }
2131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 ActivityThread() {
Craig Mautner88c05892013-06-28 09:47:45 -07002133 mResourcesManager = ResourcesManager.getInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 }
2135
2136 public ApplicationThread getApplicationThread()
2137 {
2138 return mAppThread;
2139 }
2140
2141 public Instrumentation getInstrumentation()
2142 {
2143 return mInstrumentation;
2144 }
2145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002147 return mProfiler != null && mProfiler.profileFile != null
2148 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 }
2150
2151 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002152 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 }
2154
2155 public Looper getLooper() {
2156 return mLooper;
2157 }
2158
2159 public Application getApplication() {
2160 return mInitialApplication;
2161 }
Bob Leee5408332009-09-04 18:31:17 -07002162
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002163 public String getProcessName() {
2164 return mBoundApplication.processName;
2165 }
Bob Leee5408332009-09-04 18:31:17 -07002166
Dianne Hackborn21556372010-02-04 16:34:40 -08002167 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 synchronized (this) {
2169 if (mSystemContext == null) {
Jeff Browndefd4a62014-03-10 21:24:37 -07002170 mSystemContext = ContextImpl.createSystemContext(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 }
Jeff Browndefd4a62014-03-10 21:24:37 -07002172 return mSystemContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 }
2175
Adam Lesinskia82b6262017-03-21 16:56:17 -07002176 public ContextImpl getSystemUiContext() {
2177 synchronized (this) {
2178 if (mSystemUiContext == null) {
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002179 mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
Adam Lesinskia82b6262017-03-21 16:56:17 -07002180 }
2181 return mSystemUiContext;
2182 }
2183 }
2184
Narayan Kamath29564cd2014-08-07 10:57:40 +01002185 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Mike Cleron432b7132009-09-24 15:28:29 -07002186 synchronized (this) {
Narayan Kamath29564cd2014-08-07 10:57:40 +01002187 getSystemContext().installSystemApplicationInfo(info, classLoader);
Adam Lesinskia82b6262017-03-21 16:56:17 -07002188 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002189
2190 // give ourselves a default profiler
2191 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07002192 }
2193 }
2194
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002195 void ensureJitEnabled() {
2196 if (!mJitEnabled) {
2197 mJitEnabled = true;
2198 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
2199 }
2200 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 void scheduleGcIdler() {
2203 if (!mGcIdlerScheduled) {
2204 mGcIdlerScheduled = true;
2205 Looper.myQueue().addIdleHandler(mGcIdler);
2206 }
2207 mH.removeMessages(H.GC_WHEN_IDLE);
2208 }
2209
2210 void unscheduleGcIdler() {
2211 if (mGcIdlerScheduled) {
2212 mGcIdlerScheduled = false;
2213 Looper.myQueue().removeIdleHandler(mGcIdler);
2214 }
2215 mH.removeMessages(H.GC_WHEN_IDLE);
2216 }
2217
2218 void doGcIfNeeded() {
2219 mGcIdlerScheduled = false;
2220 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002221 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222 // + "m now=" + now);
2223 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002224 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 BinderInternal.forceGc("bg");
2226 }
2227 }
2228
Dianne Hackborne77187d2013-10-25 16:32:41 -07002229 private static final String HEAP_FULL_COLUMN
2230 = "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2231 private static final String HEAP_COLUMN
2232 = "%13s %8s %8s %8s %8s %8s %8s %8s";
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002233 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2234 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
2235 private static final String ONE_COUNT_COLUMN_HEADER = "%21s %8s";
Dianne Hackborne77187d2013-10-25 16:32:41 -07002236
2237 // Formatting for checkin service - update version if row format changes
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002238 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002239
2240 static void printRow(PrintWriter pw, String format, Object...objs) {
2241 pw.println(String.format(format, objs));
2242 }
2243
2244 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002245 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2246 int pid, String processName,
Dianne Hackborne77187d2013-10-25 16:32:41 -07002247 long nativeMax, long nativeAllocated, long nativeFree,
2248 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2249
2250 // For checkin, we print one long comma-separated list of values
2251 if (checkin) {
2252 // NOTE: if you change anything significant below, also consider changing
2253 // ACTIVITY_THREAD_CHECKIN_VERSION.
2254
2255 // Header
2256 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2257 pw.print(pid); pw.print(',');
2258 pw.print(processName); pw.print(',');
2259
2260 // Heap info - max
2261 pw.print(nativeMax); pw.print(',');
2262 pw.print(dalvikMax); pw.print(',');
2263 pw.print("N/A,");
2264 pw.print(nativeMax + dalvikMax); pw.print(',');
2265
2266 // Heap info - allocated
2267 pw.print(nativeAllocated); pw.print(',');
2268 pw.print(dalvikAllocated); pw.print(',');
2269 pw.print("N/A,");
2270 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2271
2272 // Heap info - free
2273 pw.print(nativeFree); pw.print(',');
2274 pw.print(dalvikFree); pw.print(',');
2275 pw.print("N/A,");
2276 pw.print(nativeFree + dalvikFree); pw.print(',');
2277
2278 // Heap info - proportional set size
2279 pw.print(memInfo.nativePss); pw.print(',');
2280 pw.print(memInfo.dalvikPss); pw.print(',');
2281 pw.print(memInfo.otherPss); pw.print(',');
2282 pw.print(memInfo.getTotalPss()); pw.print(',');
2283
2284 // Heap info - swappable set size
2285 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2286 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2287 pw.print(memInfo.otherSwappablePss); pw.print(',');
2288 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2289
2290 // Heap info - shared dirty
2291 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2292 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2293 pw.print(memInfo.otherSharedDirty); pw.print(',');
2294 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2295
2296 // Heap info - shared clean
2297 pw.print(memInfo.nativeSharedClean); pw.print(',');
2298 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2299 pw.print(memInfo.otherSharedClean); pw.print(',');
2300 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2301
2302 // Heap info - private Dirty
2303 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2304 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2305 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2306 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2307
2308 // Heap info - private Clean
2309 pw.print(memInfo.nativePrivateClean); pw.print(',');
2310 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2311 pw.print(memInfo.otherPrivateClean); pw.print(',');
2312 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2313
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002314 // Heap info - swapped out
2315 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2316 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2317 pw.print(memInfo.otherSwappedOut); pw.print(',');
2318 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2319
2320 // Heap info - swapped out pss
2321 if (memInfo.hasSwappedOutPss) {
2322 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2323 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2324 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2325 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2326 } else {
2327 pw.print("N/A,");
2328 pw.print("N/A,");
2329 pw.print("N/A,");
2330 pw.print("N/A,");
2331 }
2332
Dianne Hackborne77187d2013-10-25 16:32:41 -07002333 // Heap info - other areas
2334 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2335 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2336 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2337 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2338 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2339 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2340 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2341 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002342 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2343 if (memInfo.hasSwappedOutPss) {
2344 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2345 } else {
2346 pw.print("N/A,");
2347 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002348 }
2349 return;
2350 }
2351
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002352 if (!dumpSummaryOnly) {
2353 if (dumpFullInfo) {
2354 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002355 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2356 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002357 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
Martijn Coenene0764852016-01-07 17:04:22 -08002358 "Clean", "Clean", "Dirty",
2359 "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002360 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
2361 "------", "------", "------", "------", "------", "------");
2362 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2363 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2364 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002365 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002366 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002367 nativeMax, nativeAllocated, nativeFree);
2368 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2369 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2370 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002371 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002372 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002373 dalvikMax, dalvikAllocated, dalvikFree);
2374 } else {
2375 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002376 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2377 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002378 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
2379 "Clean", "Dirty", "Size", "Alloc", "Free");
2380 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
2381 "------", "------", "------", "------", "------");
2382 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2383 memInfo.nativePrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002384 memInfo.nativePrivateClean,
2385 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
2386 memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002387 nativeMax, nativeAllocated, nativeFree);
2388 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2389 memInfo.dalvikPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002390 memInfo.dalvikPrivateClean,
2391 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
2392 memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002393 dalvikMax, dalvikAllocated, dalvikFree);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002394 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002395
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002396 int otherPss = memInfo.otherPss;
2397 int otherSwappablePss = memInfo.otherSwappablePss;
2398 int otherSharedDirty = memInfo.otherSharedDirty;
2399 int otherPrivateDirty = memInfo.otherPrivateDirty;
2400 int otherSharedClean = memInfo.otherSharedClean;
2401 int otherPrivateClean = memInfo.otherPrivateClean;
2402 int otherSwappedOut = memInfo.otherSwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002403 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002404
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002405 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002406 final int myPss = memInfo.getOtherPss(i);
2407 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2408 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2409 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2410 final int mySharedClean = memInfo.getOtherSharedClean(i);
2411 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2412 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002413 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002414 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002415 || mySharedClean != 0 || myPrivateClean != 0
2416 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002417 if (dumpFullInfo) {
2418 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2419 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002420 mySharedClean, myPrivateClean,
2421 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2422 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002423 } else {
2424 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2425 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002426 myPrivateClean,
2427 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2428 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002429 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002430 otherPss -= myPss;
2431 otherSwappablePss -= mySwappablePss;
2432 otherSharedDirty -= mySharedDirty;
2433 otherPrivateDirty -= myPrivateDirty;
2434 otherSharedClean -= mySharedClean;
2435 otherPrivateClean -= myPrivateClean;
2436 otherSwappedOut -= mySwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002437 otherSwappedOutPss -= mySwappedOutPss;
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002438 }
2439 }
2440
2441 if (dumpFullInfo) {
2442 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
2443 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002444 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
2445 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002446 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
2447 memInfo.getTotalSwappablePss(),
2448 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2449 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
Thierry Strudel9b511602016-02-25 17:46:38 -08002450 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
2451 memInfo.getTotalSwappedOut(),
Martijn Coenene0764852016-01-07 17:04:22 -08002452 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
2453 nativeFree+dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002454 } else {
2455 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
Martijn Coenene0764852016-01-07 17:04:22 -08002456 otherPrivateDirty, otherPrivateClean,
2457 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002458 "", "", "");
2459 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
2460 memInfo.getTotalPrivateDirty(),
2461 memInfo.getTotalPrivateClean(),
Martijn Coenene0764852016-01-07 17:04:22 -08002462 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002463 memInfo.getTotalSwappedOut(),
2464 nativeMax+dalvikMax,
2465 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
2466 }
2467
2468 if (dumpDalvik) {
2469 pw.println(" ");
2470 pw.println(" Dalvik Details");
2471
2472 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
2473 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
2474 final int myPss = memInfo.getOtherPss(i);
2475 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2476 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2477 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2478 final int mySharedClean = memInfo.getOtherSharedClean(i);
2479 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2480 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002481 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002482 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002483 || mySharedClean != 0 || myPrivateClean != 0
2484 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002485 if (dumpFullInfo) {
2486 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2487 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002488 mySharedClean, myPrivateClean,
2489 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2490 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002491 } else {
2492 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2493 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002494 myPrivateClean,
2495 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2496 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002497 }
2498 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002499 }
2500 }
2501 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002502
2503 pw.println(" ");
2504 pw.println(" App Summary");
2505 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "Pss(KB)");
2506 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "------");
2507 printRow(pw, ONE_COUNT_COLUMN,
2508 "Java Heap:", memInfo.getSummaryJavaHeap());
2509 printRow(pw, ONE_COUNT_COLUMN,
2510 "Native Heap:", memInfo.getSummaryNativeHeap());
2511 printRow(pw, ONE_COUNT_COLUMN,
2512 "Code:", memInfo.getSummaryCode());
2513 printRow(pw, ONE_COUNT_COLUMN,
2514 "Stack:", memInfo.getSummaryStack());
2515 printRow(pw, ONE_COUNT_COLUMN,
2516 "Graphics:", memInfo.getSummaryGraphics());
2517 printRow(pw, ONE_COUNT_COLUMN,
2518 "Private Other:", memInfo.getSummaryPrivateOther());
2519 printRow(pw, ONE_COUNT_COLUMN,
2520 "System:", memInfo.getSummarySystem());
2521 pw.println(" ");
Martijn Coenene0764852016-01-07 17:04:22 -08002522 if (memInfo.hasSwappedOutPss) {
2523 printRow(pw, TWO_COUNT_COLUMNS,
2524 "TOTAL:", memInfo.getSummaryTotalPss(),
2525 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
2526 } else {
2527 printRow(pw, TWO_COUNT_COLUMNS,
2528 "TOTAL:", memInfo.getSummaryTotalPss(),
2529 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
2530 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002531 }
2532
Jeff Hamilton52d32032011-01-08 15:31:26 -06002533 public void registerOnActivityPausedListener(Activity activity,
2534 OnActivityPausedListener listener) {
2535 synchronized (mOnPauseListeners) {
2536 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2537 if (list == null) {
2538 list = new ArrayList<OnActivityPausedListener>();
2539 mOnPauseListeners.put(activity, list);
2540 }
2541 list.add(listener);
2542 }
2543 }
2544
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08002545 public void unregisterOnActivityPausedListener(Activity activity,
2546 OnActivityPausedListener listener) {
2547 synchronized (mOnPauseListeners) {
2548 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2549 if (list != null) {
2550 list.remove(listener);
2551 }
2552 }
2553 }
2554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 public final ActivityInfo resolveActivityInfo(Intent intent) {
2556 ActivityInfo aInfo = intent.resolveActivityInfo(
2557 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2558 if (aInfo == null) {
2559 // Throw an exception.
2560 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002561 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 }
2563 return aInfo;
2564 }
Bob Leee5408332009-09-04 18:31:17 -07002565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002568 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002569 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002571 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 r.intent = intent;
2573 r.state = state;
2574 r.parent = parent;
2575 r.embeddedID = id;
2576 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002577 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 if (localLOGV) {
2579 ComponentName compname = intent.getComponent();
2580 String name;
2581 if (compname != null) {
2582 name = compname.toShortString();
2583 } else {
2584 name = "(Intent " + intent + ").getComponent() returned null";
2585 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002586 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 + ", comp=" + name
2588 + ", token=" + token);
2589 }
Craig Mautner233ceee2014-05-09 17:05:11 -07002590 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
2592
2593 public final Activity getActivity(IBinder token) {
2594 return mActivities.get(token).activity;
2595 }
2596
2597 public final void sendActivityResult(
2598 IBinder token, String id, int requestCode,
2599 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002600 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07002601 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2603 list.add(new ResultInfo(id, requestCode, resultCode, data));
2604 mAppThread.scheduleSendResult(token, list);
2605 }
2606
Jeff Brown9ef09972013-10-15 20:49:59 -07002607 private void sendMessage(int what, Object obj) {
2608 sendMessage(what, obj, 0, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 }
2610
Jeff Brown9ef09972013-10-15 20:49:59 -07002611 private void sendMessage(int what, Object obj, int arg1) {
2612 sendMessage(what, obj, arg1, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 }
2614
Jeff Brown9ef09972013-10-15 20:49:59 -07002615 private void sendMessage(int what, Object obj, int arg1, int arg2) {
2616 sendMessage(what, obj, arg1, arg2, false);
2617 }
2618
2619 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
2620 if (DEBUG_MESSAGES) Slog.v(
2621 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2622 + ": " + arg1 + " / " + obj);
2623 Message msg = Message.obtain();
2624 msg.what = what;
2625 msg.obj = obj;
2626 msg.arg1 = arg1;
2627 msg.arg2 = arg2;
2628 if (async) {
2629 msg.setAsynchronous(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 }
Jeff Brown9ef09972013-10-15 20:49:59 -07002631 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 }
2633
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07002634 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
2635 if (DEBUG_MESSAGES) Slog.v(
2636 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
2637 "seq= " + seq);
2638 Message msg = Message.obtain();
2639 msg.what = what;
2640 SomeArgs args = SomeArgs.obtain();
2641 args.arg1 = obj;
2642 args.argi1 = arg1;
2643 args.argi2 = arg2;
2644 args.argi3 = seq;
2645 msg.obj = args;
2646 mH.sendMessage(msg);
2647 }
2648
Dianne Hackborn21556372010-02-04 16:34:40 -08002649 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 String what) {
2651 ContextCleanupInfo cci = new ContextCleanupInfo();
2652 cci.context = context;
2653 cci.who = who;
2654 cci.what = what;
Jeff Brown9ef09972013-10-15 20:49:59 -07002655 sendMessage(H.CLEAN_UP_CONTEXT, cci);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 }
2657
Craig Mautner233ceee2014-05-09 17:05:11 -07002658 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
2660
2661 ActivityInfo aInfo = r.activityInfo;
2662 if (r.packageInfo == null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002663 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 Context.CONTEXT_INCLUDE_CODE);
2665 }
Bob Leee5408332009-09-04 18:31:17 -07002666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 ComponentName component = r.intent.getComponent();
2668 if (component == null) {
2669 component = r.intent.resolveActivity(
2670 mInitialApplication.getPackageManager());
2671 r.intent.setComponent(component);
2672 }
2673
2674 if (r.activityInfo.targetActivity != null) {
2675 component = new ComponentName(r.activityInfo.packageName,
2676 r.activityInfo.targetActivity);
2677 }
2678
Adam Lesinski4e862812016-11-21 16:02:24 -08002679 ContextImpl appContext = createBaseContextForActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 Activity activity = null;
2681 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08002682 java.lang.ClassLoader cl = appContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04002683 activity = mInstrumentation.newActivity(
2684 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002685 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 r.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01002687 r.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 if (r.state != null) {
2689 r.state.setClassLoader(cl);
2690 }
2691 } catch (Exception e) {
2692 if (!mInstrumentation.onException(activity, e)) {
2693 throw new RuntimeException(
2694 "Unable to instantiate activity " + component
2695 + ": " + e.toString(), e);
2696 }
2697 }
2698
2699 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002700 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002701
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002702 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
2703 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 TAG, r + ": app=" + app
2705 + ", appName=" + app.getPackageName()
2706 + ", pkg=" + r.packageInfo.getPackageName()
2707 + ", comp=" + r.intent.getComponent().toShortString()
2708 + ", dir=" + r.packageInfo.getAppDir());
2709
2710 if (activity != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002712 Configuration config = new Configuration(mCompatConfiguration);
Andrii Kuliand0ad9382016-04-18 20:54:20 -07002713 if (r.overrideConfig != null) {
2714 config.updateFrom(r.overrideConfig);
2715 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002716 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002717 + r.activityInfo.name + " with config " + config);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07002718 Window window = null;
2719 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
2720 window = r.mPendingRemoveWindow;
2721 r.mPendingRemoveWindow = null;
2722 r.mPendingRemoveWindowManager = null;
2723 }
Adam Lesinski4e862812016-11-21 16:02:24 -08002724 appContext.setOuterContext(activity);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002725 activity.attach(appContext, this, getInstrumentation(), r.token,
2726 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Craig Mautner233ceee2014-05-09 17:05:11 -07002727 r.embeddedID, r.lastNonConfigurationInstances, config,
Andrii Kulian51c1b672017-04-07 18:39:32 -07002728 r.referrer, r.voiceInteractor, window, r.configCallback);
Bob Leee5408332009-09-04 18:31:17 -07002729
Christopher Tateb70f3df2009-04-07 16:07:59 -07002730 if (customIntent != null) {
2731 activity.mIntent = customIntent;
2732 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002733 r.lastNonConfigurationInstances = null;
Sudheer Shanka84a48952017-03-08 18:19:01 -08002734 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 activity.mStartedActivity = false;
2736 int theme = r.activityInfo.getThemeResource();
2737 if (theme != 0) {
2738 activity.setTheme(theme);
2739 }
2740
2741 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07002742 if (r.isPersistable()) {
2743 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
2744 } else {
2745 mInstrumentation.callActivityOnCreate(activity, r.state);
2746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 if (!activity.mCalled) {
2748 throw new SuperNotCalledException(
2749 "Activity " + r.intent.getComponent().toShortString() +
2750 " did not call through to super.onCreate()");
2751 }
2752 r.activity = activity;
2753 r.stopped = true;
2754 if (!r.activity.mFinished) {
2755 activity.performStart();
2756 r.stopped = false;
2757 }
2758 if (!r.activity.mFinished) {
Craig Mautnera0026042014-04-23 11:45:37 -07002759 if (r.isPersistable()) {
2760 if (r.state != null || r.persistentState != null) {
2761 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
2762 r.persistentState);
2763 }
2764 } else if (r.state != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2766 }
2767 }
2768 if (!r.activity.mFinished) {
2769 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07002770 if (r.isPersistable()) {
2771 mInstrumentation.callActivityOnPostCreate(activity, r.state,
2772 r.persistentState);
2773 } else {
2774 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 if (!activity.mCalled) {
2777 throw new SuperNotCalledException(
2778 "Activity " + r.intent.getComponent().toShortString() +
2779 " did not call through to super.onPostCreate()");
2780 }
2781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 }
2783 r.paused = true;
2784
2785 mActivities.put(r.token, r);
2786
2787 } catch (SuperNotCalledException e) {
2788 throw e;
2789
2790 } catch (Exception e) {
2791 if (!mInstrumentation.onException(activity, e)) {
2792 throw new RuntimeException(
2793 "Unable to start activity " + component
2794 + ": " + e.toString(), e);
2795 }
2796 }
2797
2798 return activity;
2799 }
2800
Sudheer Shanka84a48952017-03-08 18:19:01 -08002801 /**
2802 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
2803 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
2804 * network rules to get updated.
2805 */
2806 private void checkAndBlockForNetworkAccess() {
2807 synchronized (mNetworkPolicyLock) {
2808 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
2809 try {
2810 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
2811 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
2812 } catch (RemoteException ignored) {}
2813 }
2814 }
2815 }
2816
Adam Lesinski4e862812016-11-21 16:02:24 -08002817 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
2818 final int displayId;
Craig Mautnere0a38842013-12-16 16:14:02 -08002819 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002820 displayId = ActivityManager.getService().getActivityDisplayId(r.token);
Craig Mautnere0a38842013-12-16 16:14:02 -08002821 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002822 throw e.rethrowFromSystemServer();
Craig Mautnere0a38842013-12-16 16:14:02 -08002823 }
Jeff Brownefd43bd2012-09-21 17:02:35 -07002824
Wale Ogunwale7c726682015-02-06 17:34:28 -08002825 ContextImpl appContext = ContextImpl.createActivityContext(
Adam Lesinski4e862812016-11-21 16:02:24 -08002826 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
Wale Ogunwale7c726682015-02-06 17:34:28 -08002827
2828 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
Jeff Brownefd43bd2012-09-21 17:02:35 -07002829 // For debugging purposes, if the activity's package name contains the value of
2830 // the "debug.use-second-display" system property as a substring, then show
2831 // its content on a secondary display if there is one.
Jeff Brownefd43bd2012-09-21 17:02:35 -07002832 String pkgName = SystemProperties.get("debug.second-display.pkg");
2833 if (pkgName != null && !pkgName.isEmpty()
2834 && r.packageInfo.mPackageName.contains(pkgName)) {
Wale Ogunwale7c726682015-02-06 17:34:28 -08002835 for (int id : dm.getDisplayIds()) {
2836 if (id != Display.DEFAULT_DISPLAY) {
Wale Ogunwale26698512015-06-05 16:55:33 -07002837 Display display =
Bryce Lee609bf652017-02-09 16:50:13 -08002838 dm.getCompatibleDisplay(id, appContext.getResources());
Adam Lesinski4e862812016-11-21 16:02:24 -08002839 appContext = (ContextImpl) appContext.createDisplayContext(display);
Jeff Brownefd43bd2012-09-21 17:02:35 -07002840 break;
2841 }
2842 }
2843 }
Adam Lesinski4e862812016-11-21 16:02:24 -08002844 return appContext;
Jeff Brownefd43bd2012-09-21 17:02:35 -07002845 }
2846
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08002847 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 // If we are getting ready to gc after going to the background, well
2849 // we are back active so skip it.
2850 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07002851 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852
Jeff Hao1b012d32014-08-20 10:35:34 -07002853 if (r.profilerInfo != null) {
2854 mProfiler.setProfiler(r.profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002855 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002856 }
2857
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002858 // Make sure we are running with the most recent config.
2859 handleConfigurationChanged(null, null);
2860
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002861 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 TAG, "Handling launch of " + r);
Adam Powellcfbe9be2013-11-06 14:58:58 -08002863
Chet Haase0d1c27a2014-11-03 18:35:16 +00002864 // Initialize before creating the activity
Jesse Hallc37984f2017-05-23 16:55:08 -07002865 if (!ThreadedRenderer.sRendererDisabled) {
2866 GraphicsEnvironment.earlyInitEGL();
2867 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00002868 WindowManagerGlobal.initialize();
2869
Craig Mautner233ceee2014-05-09 17:05:11 -07002870 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871
2872 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002873 r.createdConfig = new Configuration(mConfiguration);
Filip Gruszczynski23493322015-07-29 17:02:59 -07002874 reportSizeConfigurations(r);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002875 Bundle oldState = r.state;
Craig Mautner233ceee2014-05-09 17:05:11 -07002876 handleResumeActivity(r.token, false, r.isForward,
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08002877 !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878
2879 if (!r.activity.mFinished && r.startsNotResumed) {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07002880 // The activity manager actually wants this one to start out paused, because it
2881 // needs to be visible but isn't in the foreground. We accomplish this by going
2882 // through the normal startup (because activities expect to go through onResume()
2883 // the first time they run, before their window is displayed), and then pausing it.
2884 // However, in this case we do -not- need to do the full pause cycle (of freezing
2885 // and such) because the activity manager assumes it can just retain the current
2886 // state it has.
2887 performPauseActivityIfNeeded(r, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07002889 // We need to keep around the original state, in case we need to be created again.
2890 // But we only do this for pre-Honeycomb apps, which always save their state when
2891 // pausing, so we can not have them save their state when restarting from a paused
2892 // state. For HC and later, we want to (and can) let the state be saved as the
2893 // normal part of stopping the activity.
2894 if (r.isPreHoneycomb()) {
2895 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 }
2898 } else {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07002899 // 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 -08002900 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002901 ActivityManager.getService()
Wale Ogunwaleba7881c2015-08-01 19:28:29 -07002902 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
2903 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002905 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 }
2907 }
2908 }
2909
Filip Gruszczynski23493322015-07-29 17:02:59 -07002910 private void reportSizeConfigurations(ActivityClientRecord r) {
2911 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
2912 if (configurations == null) {
2913 return;
2914 }
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07002915 SparseIntArray horizontal = new SparseIntArray();
2916 SparseIntArray vertical = new SparseIntArray();
2917 SparseIntArray smallest = new SparseIntArray();
Filip Gruszczynski23493322015-07-29 17:02:59 -07002918 for (int i = configurations.length - 1; i >= 0; i--) {
2919 Configuration config = configurations[i];
2920 if (config.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07002921 vertical.put(config.screenHeightDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07002922 }
2923 if (config.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07002924 horizontal.put(config.screenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07002925 }
2926 if (config.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07002927 smallest.put(config.smallestScreenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07002928 }
2929 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07002930 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002931 ActivityManager.getService().reportSizeConfigurations(r.token,
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07002932 horizontal.copyKeys(), vertical.copyKeys(), smallest.copyKeys());
Filip Gruszczynski23493322015-07-29 17:02:59 -07002933 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002934 throw ex.rethrowFromSystemServer();
Filip Gruszczynski23493322015-07-29 17:02:59 -07002935 }
2936
2937 }
2938
Dianne Hackborn85d558c2014-11-04 10:31:54 -08002939 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 final int N = intents.size();
2941 for (int i=0; i<N; i++) {
Dianne Hackborna01a0fa2014-12-02 10:33:14 -08002942 ReferrerIntent intent = intents.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 intent.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01002944 intent.prepareToEnterProcess();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002945 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2947 }
2948 }
2949
Wale Ogunwale826c7062016-09-13 08:25:54 -07002950 void performNewIntents(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
2951 final ActivityClientRecord r = mActivities.get(token);
2952 if (r == null) {
2953 return;
2954 }
2955
2956 final boolean resumed = !r.paused;
2957 if (resumed) {
2958 r.activity.mTemporaryPause = true;
2959 mInstrumentation.callActivityOnPause(r.activity);
2960 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07002961 checkAndBlockForNetworkAccess();
Wale Ogunwale826c7062016-09-13 08:25:54 -07002962 deliverNewIntents(r, intents);
2963 if (resumed) {
2964 r.activity.performResume();
2965 r.activity.mTemporaryPause = false;
2966 }
2967
2968 if (r.paused && andPause) {
2969 // In this case the activity was in the paused state when we delivered the intent,
2970 // to guarantee onResume gets called after onNewIntent we temporarily resume the
2971 // activity and pause again as the caller wanted.
2972 performResumeActivity(token, false, "performNewIntents");
2973 performPauseActivityIfNeeded(r, "performNewIntents");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
2975 }
Bob Leee5408332009-09-04 18:31:17 -07002976
Romain Guy65b345f2011-07-27 18:51:50 -07002977 private void handleNewIntent(NewIntentData data) {
Wale Ogunwale826c7062016-09-13 08:25:54 -07002978 performNewIntents(data.token, data.intents, data.andPause);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 }
2980
Adam Skorydfc7fd72013-08-05 19:23:41 -07002981 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
Felipe Leme640f30a2017-03-06 15:44:06 -08002982 // Filling for autofill has a few differences:
Felipe Leme1ca634a2016-11-28 17:21:21 -08002983 // - it does not need an AssistContent
2984 // - it does not call onProvideAssistData()
2985 // - it needs an IAutoFillCallback
Felipe Leme640f30a2017-03-06 15:44:06 -08002986 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
Felipe Leme1ca634a2016-11-28 17:21:21 -08002987
Felipe Leme85d1c2d2017-04-21 08:56:04 -07002988 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani4f128e42016-05-10 11:44:12 -07002989 if (mLastSessionId != cmd.sessionId) {
2990 // Clear the existing structures
2991 mLastSessionId = cmd.sessionId;
2992 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
2993 AssistStructure structure = mLastAssistStructures.get(i).get();
2994 if (structure != null) {
2995 structure.clearSendChannel();
2996 }
2997 mLastAssistStructures.remove(i);
Dianne Hackborn782d4982015-07-08 17:36:37 -07002998 }
2999 }
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003000
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003001 Bundle data = new Bundle();
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003002 AssistStructure structure = null;
Felipe Leme640f30a2017-03-06 15:44:06 -08003003 AssistContent content = forAutofill ? null : new AssistContent();
Amith Yamasani858f98d2017-02-22 12:59:53 -08003004 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003005 ActivityClientRecord r = mActivities.get(cmd.activityToken);
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003006 Uri referrer = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003007 if (r != null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003008 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003009 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003010 r.activity.onProvideAssistData(data);
Felipe Leme6d553872016-12-08 17:13:25 -08003011 referrer = r.activity.onProvideReferrer();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003012 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003013 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill) {
Svet Ganovfd31f852017-04-26 15:54:27 -07003014 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
Adam Skory4aaed142015-04-22 11:29:31 -06003015 Intent activityIntent = r.activity.getIntent();
Felipe Leme6d553872016-12-08 17:13:25 -08003016 boolean notSecure = r.window == null ||
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003017 (r.window.getAttributes().flags
Felipe Leme6d553872016-12-08 17:13:25 -08003018 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3019 if (activityIntent != null && notSecure) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003020 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003021 Intent intent = new Intent(activityIntent);
3022 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3023 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3024 intent.removeUnsafeExtras();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003025 content.setDefaultIntent(intent);
3026 }
Adam Skory4aaed142015-04-22 11:29:31 -06003027 } else {
Felipe Leme640f30a2017-03-06 15:44:06 -08003028 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003029 content.setDefaultIntent(new Intent());
3030 }
Adam Skory4aaed142015-04-22 11:29:31 -06003031 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003032 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003033 r.activity.onProvideAssistContent(content);
3034 }
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07003035 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003036 }
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003037 if (structure == null) {
3038 structure = new AssistStructure();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003039 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08003040
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003041 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani858f98d2017-02-22 12:59:53 -08003042
3043 structure.setAcquisitionStartTime(startTime);
3044 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3045
Amith Yamasani4f128e42016-05-10 11:44:12 -07003046 mLastAssistStructures.add(new WeakReference<>(structure));
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003047 IActivityManager mgr = ActivityManager.getService();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003048 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003049 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003050 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003051 throw e.rethrowFromSystemServer();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003052 }
3053 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07003054
3055 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
3056 ActivityClientRecord r = mActivities.get(token);
3057 if (r != null) {
3058 r.activity.onTranslucentConversionComplete(drawComplete);
3059 }
3060 }
3061
Craig Mautnereb8abf72014-07-02 15:04:09 -07003062 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
3063 ActivityClientRecord r = mActivities.get(token);
3064 if (r != null) {
3065 r.activity.onNewActivityOptions(options);
3066 }
3067 }
3068
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003069 public void handleInstallProvider(ProviderInfo info) {
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003070 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3071 try {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003072 installContentProviders(mInitialApplication, Arrays.asList(info));
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003073 } finally {
3074 StrictMode.setThreadPolicy(oldPolicy);
3075 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003076 }
3077
Craig Mautner8746a472014-07-24 15:12:54 -07003078 private void handleEnterAnimationComplete(IBinder token) {
3079 ActivityClientRecord r = mActivities.get(token);
3080 if (r != null) {
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08003081 r.activity.dispatchEnterAnimationComplete();
Craig Mautner8746a472014-07-24 15:12:54 -07003082 }
3083 }
3084
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04003085 private void handleStartBinderTracking() {
3086 Binder.enableTracing();
3087 }
3088
3089 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
3090 try {
3091 Binder.disableTracing();
3092 Binder.getTransactionTracker().writeTracesToFile(fd);
3093 } finally {
3094 IoUtils.closeQuietly(fd);
3095 Binder.getTransactionTracker().clearTraces();
3096 }
3097 }
3098
Winson Chung5af42fc2017-03-24 17:11:33 -07003099 private void handleMultiWindowModeChanged(IBinder token, boolean isInMultiWindowMode,
3100 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003101 final ActivityClientRecord r = mActivities.get(token);
3102 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003103 final Configuration newConfig = new Configuration(mConfiguration);
3104 if (overrideConfig != null) {
3105 newConfig.updateFrom(overrideConfig);
3106 }
3107 r.activity.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003108 }
3109 }
3110
Winson Chung5af42fc2017-03-24 17:11:33 -07003111 private void handlePictureInPictureModeChanged(IBinder token, boolean isInPipMode,
3112 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003113 final ActivityClientRecord r = mActivities.get(token);
3114 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003115 final Configuration newConfig = new Configuration(mConfiguration);
3116 if (overrideConfig != null) {
3117 newConfig.updateFrom(overrideConfig);
3118 }
3119 r.activity.dispatchPictureInPictureModeChanged(isInPipMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003120 }
3121 }
3122
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003123 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
3124 final ActivityClientRecord r = mActivities.get(token);
3125 if (r != null) {
3126 r.voiceInteractor = interactor;
3127 r.activity.setVoiceInteractor(interactor);
3128 if (interactor == null) {
3129 r.activity.onLocalVoiceInteractionStopped();
3130 } else {
3131 r.activity.onLocalVoiceInteractionStarted();
3132 }
3133 }
3134 }
3135
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003136 static final void handleAttachAgent(String agent) {
3137 try {
3138 VMDebug.attachAgent(agent);
3139 } catch (IOException e) {
3140 Slog.e(TAG, "Attaching agent failed: " + agent);
3141 }
3142 }
3143
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003144 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
3145
3146 /**
3147 * Return the Intent that's currently being handled by a
3148 * BroadcastReceiver on this thread, or null if none.
3149 * @hide
3150 */
3151 public static Intent getIntentBeingBroadcast() {
3152 return sCurrentBroadcastIntent.get();
3153 }
3154
Romain Guy65b345f2011-07-27 18:51:50 -07003155 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 // If we are getting ready to gc after going to the background, well
3157 // we are back active so skip it.
3158 unscheduleGcIdler();
3159
3160 String component = data.intent.getComponent().getClassName();
3161
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003162 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003163 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003165 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166
Adam Lesinski4e862812016-11-21 16:02:24 -08003167 Application app;
Romain Guy65b345f2011-07-27 18:51:50 -07003168 BroadcastReceiver receiver;
Adam Lesinski4e862812016-11-21 16:02:24 -08003169 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08003171 app = packageInfo.makeApplication(false, mInstrumentation);
3172 context = (ContextImpl) app.getBaseContext();
3173 if (data.info.splitName != null) {
3174 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
3175 }
3176 java.lang.ClassLoader cl = context.getClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 data.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003178 data.intent.prepareToEnterProcess();
Dianne Hackborne829fef2010-10-26 17:44:01 -07003179 data.setExtrasClassLoader(cl);
Dan Sandler07fe63e2017-08-15 16:41:11 -04003180 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003182 if (DEBUG_BROADCAST) Slog.i(TAG,
3183 "Finishing failed broadcast to " + data.intent.getComponent());
3184 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 throw new RuntimeException(
3186 "Unable to instantiate receiver " + component
3187 + ": " + e.toString(), e);
3188 }
3189
3190 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003191 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 TAG, "Performing receive of " + data.intent
3193 + ": app=" + app
3194 + ", appName=" + app.getPackageName()
3195 + ", pkg=" + packageInfo.getPackageName()
3196 + ", comp=" + data.intent.getComponent().toShortString()
3197 + ", dir=" + packageInfo.getAppDir());
3198
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003199 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07003200 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 receiver.onReceive(context.getReceiverRestrictedContext(),
3202 data.intent);
3203 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003204 if (DEBUG_BROADCAST) Slog.i(TAG,
3205 "Finishing failed broadcast to " + data.intent.getComponent());
3206 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207 if (!mInstrumentation.onException(receiver, e)) {
3208 throw new RuntimeException(
3209 "Unable to start receiver " + component
3210 + ": " + e.toString(), e);
3211 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003212 } finally {
3213 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 }
3215
Dianne Hackborne829fef2010-10-26 17:44:01 -07003216 if (receiver.getPendingResult() != null) {
3217 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 }
3219 }
3220
Christopher Tate181fafa2009-05-14 11:12:14 -07003221 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07003222 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003223 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003224
Christopher Tate346acb12012-10-15 19:20:25 -07003225 // Sanity check the requested target package's uid against ours
3226 try {
3227 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
3228 data.appInfo.packageName, 0, UserHandle.myUserId());
3229 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
3230 Slog.w(TAG, "Asked to instantiate non-matching package "
3231 + data.appInfo.packageName);
3232 return;
3233 }
3234 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003235 throw e.rethrowFromSystemServer();
Christopher Tate346acb12012-10-15 19:20:25 -07003236 }
3237
Christopher Tate181fafa2009-05-14 11:12:14 -07003238 // no longer idle; we have backup work to do
3239 unscheduleGcIdler();
3240
3241 // instantiate the BackupAgent class named in the manifest
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003242 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07003243 String packageName = packageInfo.mPackageName;
Christopher Tate346acb12012-10-15 19:20:25 -07003244 if (packageName == null) {
3245 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
3246 return;
3247 }
3248
Christopher Tate181fafa2009-05-14 11:12:14 -07003249 String classname = data.appInfo.backupAgentName;
Christopher Tate79ec80d2011-06-24 14:58:49 -07003250 // full backup operation but no app-supplied agent? use the default implementation
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003251 if (classname == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
3252 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07003253 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07003254 }
Christopher Tate4a627c72011-04-01 14:43:32 -07003255
Christopher Tate181fafa2009-05-14 11:12:14 -07003256 try {
Christopher Tated1475e02009-07-09 15:36:17 -07003257 IBinder binder = null;
Christopher Tate2e40d112014-07-15 12:37:38 -07003258 BackupAgent agent = mBackupAgents.get(packageName);
3259 if (agent != null) {
3260 // reusing the existing instance
3261 if (DEBUG_BACKUP) {
3262 Slog.v(TAG, "Reusing existing agent instance");
Christopher Tated1475e02009-07-09 15:36:17 -07003263 }
Christopher Tate2e40d112014-07-15 12:37:38 -07003264 binder = agent.onBind();
3265 } else {
3266 try {
3267 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
3268
3269 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003270 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tate2e40d112014-07-15 12:37:38 -07003271
3272 // set up the agent's context
Dan Sandler07fe63e2017-08-15 16:41:11 -04003273 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Christopher Tate2e40d112014-07-15 12:37:38 -07003274 context.setOuterContext(agent);
3275 agent.attach(context);
3276
3277 agent.onCreate();
3278 binder = agent.onBind();
3279 mBackupAgents.put(packageName, agent);
3280 } catch (Exception e) {
3281 // If this is during restore, fail silently; otherwise go
3282 // ahead and let the user see the crash.
3283 Slog.e(TAG, "Agent threw during creation: " + e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003284 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
3285 && data.backupMode !=
3286 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
Christopher Tate2e40d112014-07-15 12:37:38 -07003287 throw e;
3288 }
3289 // falling through with 'binder' still null
3290 }
Christopher Tated1475e02009-07-09 15:36:17 -07003291 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003292
3293 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07003294 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003295 ActivityManager.getService().backupAgentCreated(packageName, binder);
Christopher Tate181fafa2009-05-14 11:12:14 -07003296 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003297 throw e.rethrowFromSystemServer();
Christopher Tate181fafa2009-05-14 11:12:14 -07003298 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003299 } catch (Exception e) {
3300 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07003301 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07003302 }
3303 }
3304
3305 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07003306 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003307 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07003308
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003309 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07003310 String packageName = packageInfo.mPackageName;
3311 BackupAgent agent = mBackupAgents.get(packageName);
3312 if (agent != null) {
3313 try {
3314 agent.onDestroy();
3315 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003316 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07003317 e.printStackTrace();
3318 }
3319 mBackupAgents.remove(packageName);
3320 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003321 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003322 }
3323 }
3324
Romain Guy65b345f2011-07-27 18:51:50 -07003325 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 // If we are getting ready to gc after going to the background, well
3327 // we are back active so skip it.
3328 unscheduleGcIdler();
3329
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003330 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003331 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 Service service = null;
3333 try {
3334 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003335 service = (Service) cl.loadClass(data.info.name).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 } catch (Exception e) {
3337 if (!mInstrumentation.onException(service, e)) {
3338 throw new RuntimeException(
3339 "Unable to instantiate service " + data.info.name
3340 + ": " + e.toString(), e);
3341 }
3342 }
3343
3344 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003345 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346
Jeff Browndefd4a62014-03-10 21:24:37 -07003347 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
3348 context.setOuterContext(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349
Dan Sandler07fe63e2017-08-15 16:41:11 -04003350 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 service.attach(context, this, data.info.name, data.token, app,
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003352 ActivityManager.getService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 service.onCreate();
3354 mServices.put(data.token, service);
3355 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003356 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003357 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003359 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 }
3361 } catch (Exception e) {
3362 if (!mInstrumentation.onException(service, e)) {
3363 throw new RuntimeException(
3364 "Unable to create service " + data.info.name
3365 + ": " + e.toString(), e);
3366 }
3367 }
3368 }
3369
Romain Guy65b345f2011-07-27 18:51:50 -07003370 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07003372 if (DEBUG_SERVICE)
3373 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 if (s != null) {
3375 try {
3376 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003377 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 try {
3379 if (!data.rebind) {
3380 IBinder binder = s.onBind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003381 ActivityManager.getService().publishService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 data.token, data.intent, binder);
3383 } else {
3384 s.onRebind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003385 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003386 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003388 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003390 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 }
3392 } catch (Exception e) {
3393 if (!mInstrumentation.onException(s, e)) {
3394 throw new RuntimeException(
3395 "Unable to bind to service " + s
3396 + " with " + data.intent + ": " + e.toString(), e);
3397 }
3398 }
3399 }
3400 }
3401
Romain Guy65b345f2011-07-27 18:51:50 -07003402 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 Service s = mServices.get(data.token);
3404 if (s != null) {
3405 try {
3406 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003407 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 boolean doRebind = s.onUnbind(data.intent);
3409 try {
3410 if (doRebind) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003411 ActivityManager.getService().unbindFinished(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 data.token, data.intent, doRebind);
3413 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003414 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003415 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 }
3417 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003418 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 }
3420 } catch (Exception e) {
3421 if (!mInstrumentation.onException(s, e)) {
3422 throw new RuntimeException(
3423 "Unable to unbind to service " + s
3424 + " with " + data.intent + ": " + e.toString(), e);
3425 }
3426 }
3427 }
3428 }
3429
Dianne Hackborn625ac272010-09-17 18:29:22 -07003430 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003431 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3432 try {
3433 Service s = mServices.get(info.token);
3434 if (s != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003435 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3436 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003437 s.dump(info.fd.getFileDescriptor(), pw, info.args);
3438 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003440 } finally {
3441 IoUtils.closeQuietly(info.fd);
3442 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 }
3444 }
3445
Dianne Hackborn625ac272010-09-17 18:29:22 -07003446 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003447 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3448 try {
3449 ActivityClientRecord r = mActivities.get(info.token);
3450 if (r != null && r.activity != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003451 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3452 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003453 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
3454 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07003455 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003456 } finally {
3457 IoUtils.closeQuietly(info.fd);
3458 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07003459 }
3460 }
3461
Marco Nelissen18cb2872011-11-15 11:19:53 -08003462 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003463 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3464 try {
3465 ProviderClientRecord r = mLocalProviders.get(info.token);
3466 if (r != null && r.mLocalProvider != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003467 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3468 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003469 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
3470 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08003471 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003472 } finally {
3473 IoUtils.closeQuietly(info.fd);
3474 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08003475 }
3476 }
3477
Romain Guy65b345f2011-07-27 18:51:50 -07003478 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 Service s = mServices.get(data.token);
3480 if (s != null) {
3481 try {
3482 if (data.args != null) {
3483 data.args.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003484 data.args.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003486 int res;
3487 if (!data.taskRemoved) {
3488 res = s.onStartCommand(data.args, data.flags, data.startId);
3489 } else {
3490 s.onTaskRemoved(data.args);
3491 res = Service.START_TASK_REMOVED_COMPLETE;
3492 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003493
3494 QueuedWork.waitToFinish();
3495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003497 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003498 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003500 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003502 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 } catch (Exception e) {
3504 if (!mInstrumentation.onException(s, e)) {
3505 throw new RuntimeException(
3506 "Unable to start service " + s
3507 + " with " + data.args + ": " + e.toString(), e);
3508 }
3509 }
3510 }
3511 }
3512
Romain Guy65b345f2011-07-27 18:51:50 -07003513 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 Service s = mServices.remove(token);
3515 if (s != null) {
3516 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003517 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 s.onDestroy();
Amith Yamasani75928252017-05-22 15:10:47 -07003519 s.detachAndCleanUp();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003521 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08003523 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003525
3526 QueuedWork.waitToFinish();
3527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003529 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003530 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003532 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 }
3534 } catch (Exception e) {
3535 if (!mInstrumentation.onException(s, e)) {
3536 throw new RuntimeException(
3537 "Unable to stop service " + s
3538 + ": " + e.toString(), e);
3539 }
Craig Mautner66c4a822015-01-16 12:48:16 -08003540 Slog.i(TAG, "handleStopService: exception for " + token, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 }
Craig Mautner9776ad42015-01-15 14:38:39 -08003542 } else {
3543 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003545 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 }
3547
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003548 public final ActivityClientRecord performResumeActivity(IBinder token,
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003549 boolean clearHide, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003550 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003551 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 + " finished=" + r.activity.mFinished);
3553 if (r != null && !r.activity.mFinished) {
3554 if (clearHide) {
3555 r.hideForNow = false;
3556 r.activity.mStartedActivity = false;
3557 }
3558 try {
Dianne Hackborn6bdd3a12015-08-05 15:01:28 -07003559 r.activity.onStateNotSaved();
Dianne Hackborn689586d2012-10-01 18:23:04 -07003560 r.activity.mFragments.noteStateNotSaved();
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003561 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 if (r.pendingIntents != null) {
3563 deliverNewIntents(r, r.pendingIntents);
3564 r.pendingIntents = null;
3565 }
3566 if (r.pendingResults != null) {
3567 deliverResults(r, r.pendingResults);
3568 r.pendingResults = null;
3569 }
3570 r.activity.performResume();
3571
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01003572 synchronized (mResourcesManager) {
3573 // If there is a pending local relaunch that was requested when the activity was
3574 // paused, it will put the activity into paused state when it finally happens.
3575 // Since the activity resumed before being relaunched, we don't want that to
3576 // happen, so we need to clear the request to relaunch paused.
3577 for (int i = mRelaunchingActivities.size() - 1; i >= 0; i--) {
3578 final ActivityClientRecord relaunching = mRelaunchingActivities.get(i);
3579 if (relaunching.token == r.token
3580 && relaunching.onlyLocalRequest && relaunching.startsNotResumed) {
3581 relaunching.startsNotResumed = false;
3582 }
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08003583 }
3584 }
3585
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003586 EventLog.writeEvent(LOG_AM_ON_RESUME_CALLED, UserHandle.myUserId(),
3587 r.activity.getComponentName().getClassName(), reason);
Bob Leee5408332009-09-04 18:31:17 -07003588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 r.paused = false;
3590 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 r.state = null;
Craig Mautnera0026042014-04-23 11:45:37 -07003592 r.persistentState = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 } catch (Exception e) {
3594 if (!mInstrumentation.onException(r.activity, e)) {
3595 throw new RuntimeException(
3596 "Unable to resume activity "
3597 + r.intent.getComponent().toShortString()
3598 + ": " + e.toString(), e);
3599 }
3600 }
3601 }
3602 return r;
3603 }
3604
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003605 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
3606 if (r.mPreserveWindow && !force) {
3607 return;
3608 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003609 if (r.mPendingRemoveWindow != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003610 r.mPendingRemoveWindowManager.removeViewImmediate(
3611 r.mPendingRemoveWindow.getDecorView());
3612 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003613 if (wtoken != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07003614 WindowManagerGlobal.getInstance().closeAll(wtoken,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003615 r.activity.getClass().getName(), "Activity");
3616 }
3617 }
3618 r.mPendingRemoveWindow = null;
3619 r.mPendingRemoveWindowManager = null;
3620 }
3621
Craig Mautner233ceee2014-05-09 17:05:11 -07003622 final void handleResumeActivity(IBinder token,
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003623 boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07003624 ActivityClientRecord r = mActivities.get(token);
3625 if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) {
3626 return;
3627 }
3628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 // If we are getting ready to gc after going to the background, well
3630 // we are back active so skip it.
3631 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003632 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633
Adam Powellcfbe9be2013-11-06 14:58:58 -08003634 // TODO Push resumeArgs into the activity for consideration
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003635 r = performResumeActivity(token, clearHide, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636
3637 if (r != null) {
3638 final Activity a = r.activity;
3639
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003640 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 TAG, "Resume " + r + " started activity: " +
3642 a.mStartedActivity + ", hideForNow: " + r.hideForNow
3643 + ", finished: " + a.mFinished);
3644
3645 final int forwardBit = isForward ?
3646 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07003647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 // If the window hasn't yet been added to the window manager,
3649 // and this guy didn't finish itself or start another activity,
3650 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003651 boolean willBeVisible = !a.mStartedActivity;
3652 if (!willBeVisible) {
3653 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003654 willBeVisible = ActivityManager.getService().willActivityBeVisible(
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003655 a.getActivityToken());
3656 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003657 throw e.rethrowFromSystemServer();
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003658 }
3659 }
3660 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 r.window = r.activity.getWindow();
3662 View decor = r.window.getDecorView();
3663 decor.setVisibility(View.INVISIBLE);
3664 ViewManager wm = a.getWindowManager();
3665 WindowManager.LayoutParams l = r.window.getAttributes();
3666 a.mDecor = decor;
3667 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
3668 l.softInputMode |= forwardBit;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003669 if (r.mPreserveWindow) {
3670 a.mWindowAdded = true;
3671 r.mPreserveWindow = false;
Robert Carrb2594852016-04-25 16:21:13 -07003672 // Normally the ViewRoot sets up callbacks with the Activity
3673 // in addView->ViewRootImpl#setView. If we are instead reusing
3674 // the decor view we have to notify the view root that the
3675 // callbacks may have changed.
3676 ViewRootImpl impl = decor.getViewRootImpl();
Robert Carr311ecba2016-04-27 12:59:45 -07003677 if (impl != null) {
3678 impl.notifyChildRebuilt();
3679 }
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003680 }
Bryce Lee4b51b322017-04-07 10:27:19 -07003681 if (a.mVisibleFromClient) {
3682 if (!a.mWindowAdded) {
3683 a.mWindowAdded = true;
3684 wm.addView(decor, l);
3685 } else {
3686 // The activity will get a callback for this {@link LayoutParams} change
3687 // earlier. However, at that time the decor will not be set (this is set
3688 // in this method), so no action will be taken. This call ensures the
3689 // callback occurs with the decor set.
3690 a.onWindowAttributesChanged(l);
3691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 }
3693
3694 // If the window has already been added, but during resume
3695 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003696 // window visible.
3697 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003698 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 TAG, "Launch " + r + " mStartedActivity set");
3700 r.hideForNow = true;
3701 }
3702
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003703 // Get rid of anything left hanging around.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003704 cleanUpPendingRemoveWindows(r, false /* force */);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706 // The window is now visible if it has been added, we are not
3707 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003708 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003709 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08003711 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003712 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Adam Lesinski082614c2016-03-04 14:33:47 -08003713 + r.activityInfo.name + " with newConfig " + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 r.newConfig = null;
3715 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003716 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 + isForward);
3718 WindowManager.LayoutParams l = r.window.getAttributes();
3719 if ((l.softInputMode
3720 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
3721 != forwardBit) {
3722 l.softInputMode = (l.softInputMode
3723 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
3724 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003725 if (r.activity.mVisibleFromClient) {
3726 ViewManager wm = a.getWindowManager();
3727 View decor = r.window.getDecorView();
3728 wm.updateViewLayout(decor, l);
3729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 }
Bryce Lee4b51b322017-04-07 10:27:19 -07003731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 r.activity.mVisibleFromServer = true;
3733 mNumVisibleActivities++;
3734 if (r.activity.mVisibleFromClient) {
3735 r.activity.makeVisible();
3736 }
3737 }
3738
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003739 if (!r.onlyLocalRequest) {
3740 r.nextIdle = mNewActivities;
3741 mNewActivities = r;
3742 if (localLOGV) Slog.v(
3743 TAG, "Scheduling idle handler for " + r);
3744 Looper.myQueue().addIdleHandler(new Idler());
3745 }
3746 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747
Dianne Hackbornad9b32112012-09-17 15:35:01 -07003748 // Tell the activity manager we have resumed.
3749 if (reallyResume) {
3750 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003751 ActivityManager.getService().activityResumed(token);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07003752 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003753 throw ex.rethrowFromSystemServer();
Dianne Hackbornad9b32112012-09-17 15:35:01 -07003754 }
3755 }
3756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 } else {
3758 // If an exception was thrown when trying to resume, then
3759 // just end this activity.
3760 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003761 ActivityManager.getService()
Wale Ogunwaleba7881c2015-08-01 19:28:29 -07003762 .finishActivity(token, Activity.RESULT_CANCELED, null,
3763 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003765 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 }
3767 }
3768 }
3769
3770 private int mThumbnailWidth = -1;
3771 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003772 private Bitmap mAvailThumbnailBitmap = null;
3773 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774
Romain Guy65b345f2011-07-27 18:51:50 -07003775 private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003776 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003778 if (thumbnail == null) {
3779 int w = mThumbnailWidth;
3780 int h;
3781 if (w < 0) {
3782 Resources res = r.activity.getResources();
Winson Chung6784f1c2014-05-22 11:22:41 -07003783 int wId = com.android.internal.R.dimen.thumbnail_width;
3784 int hId = com.android.internal.R.dimen.thumbnail_height;
Winson Chungfd086222014-05-13 15:49:42 -07003785 mThumbnailWidth = w = res.getDimensionPixelSize(wId);
3786 mThumbnailHeight = h = res.getDimensionPixelSize(hId);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003787 } else {
3788 h = mThumbnailHeight;
3789 }
3790
3791 // On platforms where we don't want thumbnails, set dims to (0,0)
3792 if ((w > 0) && (h > 0)) {
Dianne Hackborndde331c2012-08-03 14:01:57 -07003793 thumbnail = Bitmap.createBitmap(r.activity.getResources().getDisplayMetrics(),
3794 w, h, THUMBNAIL_FORMAT);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003795 thumbnail.eraseColor(0);
3796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 }
3798
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08003799 if (thumbnail != null) {
3800 Canvas cv = mThumbnailCanvas;
3801 if (cv == null) {
3802 mThumbnailCanvas = cv = new Canvas();
3803 }
Tim Murraye1e6c662015-04-07 13:24:14 -07003804
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08003805 cv.setBitmap(thumbnail);
3806 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
3807 mAvailThumbnailBitmap = thumbnail;
3808 thumbnail = null;
3809 }
Dianne Hackborn6311d0a2011-08-02 16:37:58 -07003810 cv.setBitmap(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07003812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 } catch (Exception e) {
3814 if (!mInstrumentation.onException(r.activity, e)) {
3815 throw new RuntimeException(
3816 "Unable to create thumbnail of "
3817 + r.intent.getComponent().toShortString()
3818 + ": " + e.toString(), e);
3819 }
3820 thumbnail = null;
3821 }
3822
3823 return thumbnail;
3824 }
3825
Romain Guy65b345f2011-07-27 18:51:50 -07003826 private void handlePauseActivity(IBinder token, boolean finished,
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07003827 boolean userLeaving, int configChanges, boolean dontReport, int seq) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003828 ActivityClientRecord r = mActivities.get(token);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08003829 if (DEBUG_ORDER) Slog.d(TAG, "handlePauseActivity " + r + ", seq: " + seq);
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07003830 if (!checkAndUpdateLifecycleSeq(seq, r, "pauseActivity")) {
3831 return;
3832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003834 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 if (userLeaving) {
3836 performUserLeavingActivity(r);
3837 }
Bob Leee5408332009-09-04 18:31:17 -07003838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 r.activity.mConfigChangeFlags |= configChanges;
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003840 performPauseActivity(token, finished, r.isPreHoneycomb(), "handlePauseActivity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07003842 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08003843 if (r.isPreHoneycomb()) {
3844 QueuedWork.waitToFinish();
3845 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07003846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 // Tell the activity manager we have paused.
Dianne Hackborna4e102e2014-09-04 22:52:27 -07003848 if (!dontReport) {
3849 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003850 ActivityManager.getService().activityPaused(token);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07003851 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003852 throw ex.rethrowFromSystemServer();
Dianne Hackborna4e102e2014-09-04 22:52:27 -07003853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003855 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 }
3857 }
3858
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003859 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 mInstrumentation.callActivityOnUserLeaving(r.activity);
3861 }
3862
3863 final Bundle performPauseActivity(IBinder token, boolean finished,
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003864 boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003865 ActivityClientRecord r = mActivities.get(token);
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003866 return r != null ? performPauseActivity(r, finished, saveState, reason) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 }
3868
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003869 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003870 boolean saveState, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 if (r.paused) {
3872 if (r.activity.mFinished) {
3873 // If we are finishing, we won't call onResume() in certain cases.
3874 // So here we likewise don't want to call onPause() if the activity
3875 // isn't resumed.
3876 return null;
3877 }
3878 RuntimeException e = new RuntimeException(
3879 "Performing pause of activity that is not resumed: "
3880 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003881 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 if (finished) {
3884 r.activity.mFinished = true;
3885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003887 // Next have the activity save its current state and managed dialogs...
3888 if (!r.activity.mFinished && saveState) {
3889 callCallActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003891
3892 performPauseActivityIfNeeded(r, reason);
Jeff Hamilton52d32032011-01-08 15:31:26 -06003893
3894 // Notify any outstanding on paused listeners
3895 ArrayList<OnActivityPausedListener> listeners;
3896 synchronized (mOnPauseListeners) {
3897 listeners = mOnPauseListeners.remove(r.activity);
3898 }
3899 int size = (listeners != null ? listeners.size() : 0);
3900 for (int i = 0; i < size; i++) {
3901 listeners.get(i).onPaused(r.activity);
3902 }
3903
Craig Mautnera0026042014-04-23 11:45:37 -07003904 return !r.activity.mFinished && saveState ? r.state : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 }
3906
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003907 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
3908 if (r.paused) {
3909 // You are already paused silly...
3910 return;
3911 }
3912
3913 try {
3914 r.activity.mCalled = false;
3915 mInstrumentation.callActivityOnPause(r.activity);
3916 EventLog.writeEvent(LOG_AM_ON_PAUSE_CALLED, UserHandle.myUserId(),
3917 r.activity.getComponentName().getClassName(), reason);
3918 if (!r.activity.mCalled) {
3919 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
3920 + " did not call through to super.onPause()");
3921 }
3922 } catch (SuperNotCalledException e) {
3923 throw e;
3924 } catch (Exception e) {
3925 if (!mInstrumentation.onException(r.activity, e)) {
3926 throw new RuntimeException("Unable to pause activity "
3927 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
3928 }
3929 }
3930 r.paused = true;
3931 }
3932
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003933 final void performStopActivity(IBinder token, boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003934 ActivityClientRecord r = mActivities.get(token);
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003935 performStopActivityInner(r, null, false, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 }
3937
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003938 private static class StopInfo implements Runnable {
3939 ActivityClientRecord activity;
3940 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -07003941 PersistableBundle persistentState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 CharSequence description;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003943
3944 @Override public void run() {
3945 // Tell activity manager we have been stopped.
3946 try {
3947 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Reporting activity stopped: " + activity);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003948 ActivityManager.getService().activityStopped(
Craig Mautnera0026042014-04-23 11:45:37 -07003949 activity.token, state, persistentState, description);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003950 } catch (RemoteException ex) {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003951 // Dump statistics about bundle to help developers debug
3952 final LogWriter writer = new LogWriter(Log.WARN, TAG);
3953 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
3954 pw.println("Bundle stats:");
3955 Bundle.dumpStats(pw, state);
3956 pw.println("PersistableBundle stats:");
3957 Bundle.dumpStats(pw, persistentState);
3958
Jeff Sharkey369f5092016-02-29 11:16:21 -07003959 if (ex instanceof TransactionTooLargeException
Jeff Sharkey9ad86132016-03-01 11:22:59 -07003960 && activity.packageInfo.getTargetSdkVersion() < Build.VERSION_CODES.N) {
Jeff Sharkeyb8e8a912016-03-09 16:27:40 -07003961 Log.e(TAG, "App sent too much data in instance state, so it was ignored", ex);
Jeff Sharkey369f5092016-02-29 11:16:21 -07003962 return;
3963 }
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003964 throw ex.rethrowFromSystemServer();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003965 }
3966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 }
3968
Jeff Brownddaa9ac2011-11-11 20:16:14 -08003969 private static final class ProviderRefCount {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07003970 public final ContentProviderHolder holder;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003971 public final ProviderClientRecord client;
3972 public int stableCount;
3973 public int unstableCount;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08003974
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003975 // When this is set, the stable and unstable ref counts are 0 and
3976 // we have a pending operation scheduled to remove the ref count
3977 // from the activity manager. On the activity manager we are still
3978 // holding an unstable ref, though it is not reflected in the counts
3979 // here.
3980 public boolean removePending;
3981
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07003982 ProviderRefCount(ContentProviderHolder inHolder,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003983 ProviderClientRecord inClient, int sCount, int uCount) {
3984 holder = inHolder;
3985 client = inClient;
3986 stableCount = sCount;
3987 unstableCount = uCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 }
3989 }
3990
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003991 /**
3992 * Core implementation of stopping an activity. Note this is a little
3993 * tricky because the server's meaning of stop is slightly different
3994 * than our client -- for the server, stop means to save state and give
3995 * it the result when it is done, but the window may still be visible.
3996 * For the client, we want to call onStop()/onStart() to indicate when
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07003997 * the activity's UI visibility changes.
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003998 */
Romain Guy65b345f2011-07-27 18:51:50 -07003999 private void performStopActivityInner(ActivityClientRecord r,
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004000 StopInfo info, boolean keepShown, boolean saveState, String reason) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004001 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 if (r != null) {
4003 if (!keepShown && r.stopped) {
4004 if (r.activity.mFinished) {
4005 // If we are finishing, we won't call onResume() in certain
4006 // cases. So here we likewise don't want to call onStop()
4007 // if the activity isn't resumed.
4008 return;
4009 }
4010 RuntimeException e = new RuntimeException(
Andrii Kulian58178f22016-03-16 13:44:56 -07004011 "Performing stop of activity that is already stopped: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004013 Slog.e(TAG, e.getMessage(), e);
Andrii Kulian58178f22016-03-16 13:44:56 -07004014 Slog.e(TAG, r.getStateString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 }
4016
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004017 // One must first be paused before stopped...
4018 performPauseActivityIfNeeded(r, reason);
4019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 if (info != null) {
4021 try {
4022 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07004023 // For now, don't create the thumbnail here; we are
4024 // doing that by doing a screen snapshot.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 info.description = r.activity.onCreateDescription();
4026 } catch (Exception e) {
4027 if (!mInstrumentation.onException(r.activity, e)) {
4028 throw new RuntimeException(
4029 "Unable to save state of activity "
4030 + r.intent.getComponent().toShortString()
4031 + ": " + e.toString(), e);
4032 }
4033 }
4034 }
4035
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004036 // Next have the activity save its current state and managed dialogs...
4037 if (!r.activity.mFinished && saveState) {
4038 if (r.state == null) {
Craig Mautnera0026042014-04-23 11:45:37 -07004039 callCallActivityOnSaveInstanceState(r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004040 }
4041 }
4042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 if (!keepShown) {
4044 try {
4045 // Now we are idle.
Chong Zhang7687f252016-02-26 12:03:33 -08004046 r.activity.performStop(false /*preserveWindow*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 } catch (Exception e) {
4048 if (!mInstrumentation.onException(r.activity, e)) {
4049 throw new RuntimeException(
4050 "Unable to stop activity "
4051 + r.intent.getComponent().toShortString()
4052 + ": " + e.toString(), e);
4053 }
4054 }
4055 r.stopped = true;
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004056 EventLog.writeEvent(LOG_AM_ON_STOP_CALLED, UserHandle.myUserId(),
4057 r.activity.getComponentName().getClassName(), reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 }
4060 }
4061
Romain Guy65b345f2011-07-27 18:51:50 -07004062 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 View v = r.activity.mDecor;
4064 if (v != null) {
4065 if (show) {
4066 if (!r.activity.mVisibleFromServer) {
4067 r.activity.mVisibleFromServer = true;
4068 mNumVisibleActivities++;
4069 if (r.activity.mVisibleFromClient) {
4070 r.activity.makeVisible();
4071 }
4072 }
4073 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004074 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004075 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Adam Lesinski082614c2016-03-04 14:33:47 -08004076 + r.activityInfo.name + " with new config "
4077 + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 r.newConfig = null;
4079 }
4080 } else {
4081 if (r.activity.mVisibleFromServer) {
4082 r.activity.mVisibleFromServer = false;
4083 mNumVisibleActivities--;
4084 v.setVisibility(View.INVISIBLE);
4085 }
4086 }
4087 }
4088 }
4089
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004090 private void handleStopActivity(IBinder token, boolean show, int configChanges, int seq) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004091 ActivityClientRecord r = mActivities.get(token);
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004092 if (!checkAndUpdateLifecycleSeq(seq, r, "stopActivity")) {
4093 return;
4094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 r.activity.mConfigChangeFlags |= configChanges;
4096
4097 StopInfo info = new StopInfo();
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004098 performStopActivityInner(r, info, show, true, "handleStopActivity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004100 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 TAG, "Finishing stop of " + r + ": show=" + show
4102 + " win=" + r.window);
4103
4104 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07004105
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004106 // Make sure any pending writes are now committed.
4107 if (!r.isPreHoneycomb()) {
4108 QueuedWork.waitToFinish();
4109 }
4110
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07004111 // Schedule the call to tell the activity manager we have
4112 // stopped. We don't do this immediately, because we want to
4113 // have a chance for any other pending work (in particular memory
4114 // trim requests) to complete before you tell the activity
4115 // manager to proceed and allow us to go fully into the background.
4116 info.activity = r;
4117 info.state = r.state;
Craig Mautnera0026042014-04-23 11:45:37 -07004118 info.persistentState = r.persistentState;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07004119 mH.post(info);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004120 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 }
4122
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004123 private static boolean checkAndUpdateLifecycleSeq(int seq, ActivityClientRecord r,
4124 String action) {
4125 if (r == null) {
4126 return true;
4127 }
4128 if (seq < r.lastProcessedSeq) {
4129 if (DEBUG_ORDER) Slog.d(TAG, action + " for " + r + " ignored, because seq=" + seq
4130 + " < mCurrentLifecycleSeq=" + r.lastProcessedSeq);
4131 return false;
4132 }
4133 r.lastProcessedSeq = seq;
4134 return true;
4135 }
4136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004138 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 if (r.stopped) {
4140 r.activity.performRestart();
4141 r.stopped = false;
4142 }
4143 }
4144
Romain Guy65b345f2011-07-27 18:51:50 -07004145 private void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004146 ActivityClientRecord r = mActivities.get(token);
Tim Murraye1e6c662015-04-07 13:24:14 -07004147
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08004148 if (r == null) {
4149 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
4150 return;
4151 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 if (!show && !r.stopped) {
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004154 performStopActivityInner(r, null, show, false, "handleWindowVisibility");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 } else if (show && r.stopped) {
4156 // If we are getting ready to gc after going to the background, well
4157 // we are back active so skip it.
4158 unscheduleGcIdler();
4159
4160 r.activity.performRestart();
4161 r.stopped = false;
4162 }
4163 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07004164 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 TAG, "Handle window " + r + " visibility: " + show);
4166 updateVisibility(r, show);
4167 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004168 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004171 // TODO: This method should be changed to use {@link #performStopActivityInner} to perform to
4172 // stop operation on the activity to reduce code duplication and the chance of fixing a bug in
4173 // one place and missing the other.
Romain Guy65b345f2011-07-27 18:51:50 -07004174 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004175 ActivityClientRecord r = mActivities.get(token);
4176
4177 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004178 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004179 return;
4180 }
4181
4182 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004183 if (!r.stopped && !r.isPreHoneycomb()) {
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004184 if (!r.activity.mFinished && r.state == null) {
4185 callCallActivityOnSaveInstanceState(r);
4186 }
4187
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004188 try {
4189 // Now we are idle.
Chong Zhang7687f252016-02-26 12:03:33 -08004190 r.activity.performStop(false /*preserveWindow*/);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004191 } catch (Exception e) {
4192 if (!mInstrumentation.onException(r.activity, e)) {
4193 throw new RuntimeException(
4194 "Unable to stop activity "
4195 + r.intent.getComponent().toShortString()
4196 + ": " + e.toString(), e);
4197 }
4198 }
4199 r.stopped = true;
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004200 EventLog.writeEvent(LOG_AM_ON_STOP_CALLED, UserHandle.myUserId(),
4201 r.activity.getComponentName().getClassName(), "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004202 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004203
4204 // Make sure any pending writes are now committed.
4205 if (!r.isPreHoneycomb()) {
4206 QueuedWork.waitToFinish();
4207 }
4208
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004209 // Tell activity manager we slept.
4210 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004211 ActivityManager.getService().activitySlept(r.token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004212 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004213 throw ex.rethrowFromSystemServer();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004214 }
4215 } else {
4216 if (r.stopped && r.activity.mVisibleFromServer) {
4217 r.activity.performRestart();
4218 r.stopped = false;
4219 }
4220 }
4221 }
4222
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004223 private void handleSetCoreSettings(Bundle coreSettings) {
Craig Mautner88c05892013-06-28 09:47:45 -07004224 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004225 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004226 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004227 onCoreSettingsChange();
4228 }
4229
4230 private void onCoreSettingsChange() {
4231 boolean debugViewAttributes =
4232 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
4233 if (debugViewAttributes != View.mDebugViewAttributes) {
4234 View.mDebugViewAttributes = debugViewAttributes;
4235
4236 // request all activities to relaunch for the changes to take place
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004237 requestRelaunchAllActivities();
4238 }
4239 }
4240
4241 private void requestRelaunchAllActivities() {
4242 for (Map.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
4243 final Activity activity = entry.getValue().activity;
4244 if (!activity.mFinished) {
4245 try {
4246 ActivityManager.getService().requestActivityRelaunch(entry.getKey());
4247 } catch (RemoteException e) {
4248 throw e.rethrowFromSystemServer();
4249 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004250 }
4251 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004252 }
4253
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004254 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
4255 LoadedApk apk = peekPackageInfo(data.pkg, false);
4256 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004257 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004258 }
4259 apk = peekPackageInfo(data.pkg, true);
4260 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004261 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004262 }
4263 handleConfigurationChanged(mConfiguration, data.info);
Jeff Brown98365d72012-08-19 20:30:52 -07004264 WindowManagerGlobal.getInstance().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004265 }
4266
Romain Guy65b345f2011-07-27 18:51:50 -07004267 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 final int N = results.size();
4269 for (int i=0; i<N; i++) {
4270 ResultInfo ri = results.get(i);
4271 try {
4272 if (ri.mData != null) {
4273 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004274 ri.mData.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004276 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07004277 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 r.activity.dispatchActivityResult(ri.mResultWho,
4279 ri.mRequestCode, ri.mResultCode, ri.mData);
4280 } catch (Exception e) {
4281 if (!mInstrumentation.onException(r.activity, e)) {
4282 throw new RuntimeException(
4283 "Failure delivering result " + ri + " to activity "
4284 + r.intent.getComponent().toShortString()
4285 + ": " + e.toString(), e);
4286 }
4287 }
4288 }
4289 }
4290
Romain Guy65b345f2011-07-27 18:51:50 -07004291 private void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004292 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004293 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 if (r != null) {
4295 final boolean resumed = !r.paused;
4296 if (!r.activity.mFinished && r.activity.mDecor != null
4297 && r.hideForNow && resumed) {
4298 // We had hidden the activity because it started another
4299 // one... we have gotten a result back and we are not
4300 // paused, so make sure our window is visible.
4301 updateVisibility(r, true);
4302 }
4303 if (resumed) {
4304 try {
4305 // Now we are idle.
4306 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004307 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 mInstrumentation.callActivityOnPause(r.activity);
4309 if (!r.activity.mCalled) {
4310 throw new SuperNotCalledException(
4311 "Activity " + r.intent.getComponent().toShortString()
4312 + " did not call through to super.onPause()");
4313 }
4314 } catch (SuperNotCalledException e) {
4315 throw e;
4316 } catch (Exception e) {
4317 if (!mInstrumentation.onException(r.activity, e)) {
4318 throw new RuntimeException(
4319 "Unable to pause activity "
4320 + r.intent.getComponent().toShortString()
4321 + ": " + e.toString(), e);
4322 }
4323 }
4324 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07004325 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 deliverResults(r, res.results);
4327 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07004328 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004329 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 }
4331 }
4332 }
4333
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004334 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 return performDestroyActivity(token, finishing, 0, false);
4336 }
4337
Romain Guy65b345f2011-07-27 18:51:50 -07004338 private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004340 ActivityClientRecord r = mActivities.get(token);
Craig Mautner88c05892013-06-28 09:47:45 -07004341 Class<? extends Activity> activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004342 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004344 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 r.activity.mConfigChangeFlags |= configChanges;
4346 if (finishing) {
4347 r.activity.mFinished = true;
4348 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004349
4350 performPauseActivityIfNeeded(r, "destroy");
4351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 if (!r.stopped) {
4353 try {
Chong Zhang7687f252016-02-26 12:03:33 -08004354 r.activity.performStop(r.mPreserveWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004355 } catch (SuperNotCalledException e) {
4356 throw e;
4357 } catch (Exception e) {
4358 if (!mInstrumentation.onException(r.activity, e)) {
4359 throw new RuntimeException(
4360 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004361 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 + ": " + e.toString(), e);
4363 }
4364 }
4365 r.stopped = true;
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004366 EventLog.writeEvent(LOG_AM_ON_STOP_CALLED, UserHandle.myUserId(),
4367 r.activity.getComponentName().getClassName(), "destroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 }
4369 if (getNonConfigInstance) {
4370 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004371 r.lastNonConfigurationInstances
4372 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 } catch (Exception e) {
4374 if (!mInstrumentation.onException(r.activity, e)) {
4375 throw new RuntimeException(
4376 "Unable to retain activity "
4377 + r.intent.getComponent().toShortString()
4378 + ": " + e.toString(), e);
4379 }
4380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 }
4382 try {
4383 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004384 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004385 if (!r.activity.mCalled) {
4386 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004387 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 " did not call through to super.onDestroy()");
4389 }
4390 if (r.window != null) {
4391 r.window.closeAllPanels();
4392 }
4393 } catch (SuperNotCalledException e) {
4394 throw e;
4395 } catch (Exception e) {
4396 if (!mInstrumentation.onException(r.activity, e)) {
4397 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004398 "Unable to destroy activity " + safeToComponentShortString(r.intent)
4399 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 }
4401 }
4402 }
4403 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004404 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 return r;
4406 }
4407
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004408 private static String safeToComponentShortString(Intent intent) {
4409 ComponentName component = intent.getComponent();
4410 return component == null ? "[Unknown]" : component.toShortString();
4411 }
4412
Romain Guy65b345f2011-07-27 18:51:50 -07004413 private void handleDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004415 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 configChanges, getNonConfigInstance);
4417 if (r != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004418 cleanUpPendingRemoveWindows(r, finishing);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 WindowManager wm = r.activity.getWindowManager();
4420 View v = r.activity.mDecor;
4421 if (v != null) {
4422 if (r.activity.mVisibleFromServer) {
4423 mNumVisibleActivities--;
4424 }
4425 IBinder wtoken = v.getWindowToken();
4426 if (r.activity.mWindowAdded) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004427 if (r.mPreserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004428 // Hold off on removing this until the new activity's
4429 // window is being added.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004430 r.mPendingRemoveWindow = r.window;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004431 r.mPendingRemoveWindowManager = wm;
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004432 // We can only keep the part of the view hierarchy that we control,
4433 // everything else must be removed, because it might not be able to
4434 // behave properly when activity is relaunching.
4435 r.window.clearContentView();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004436 } else {
4437 wm.removeViewImmediate(v);
4438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004440 if (wtoken != null && r.mPendingRemoveWindow == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004441 WindowManagerGlobal.getInstance().closeAll(wtoken,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004442 r.activity.getClass().getName(), "Activity");
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004443 } else if (r.mPendingRemoveWindow != null) {
4444 // We're preserving only one window, others should be closed so app views
4445 // will be detached before the final tear down. It should be done now because
4446 // some components (e.g. WebView) rely on detach callbacks to perform receiver
4447 // unregister and other cleanup.
4448 WindowManagerGlobal.getInstance().closeAllExceptView(token, v,
4449 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 }
4451 r.activity.mDecor = null;
4452 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004453 if (r.mPendingRemoveWindow == null) {
4454 // If we are delaying the removal of the activity window, then
4455 // we can't clean up all windows here. Note that we can't do
4456 // so later either, which means any windows that aren't closed
4457 // by the app will leak. Well we try to warning them a lot
4458 // about leaking windows, because that is a bug, so if they are
4459 // using this recreate facility then they get to live with leaks.
Jeff Brown98365d72012-08-19 20:30:52 -07004460 WindowManagerGlobal.getInstance().closeAll(token,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004461 r.activity.getClass().getName(), "Activity");
4462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463
4464 // Mocked out contexts won't be participating in the normal
4465 // process lifecycle, but if we're running with a proper
4466 // ApplicationContext we need to have it tear down things
4467 // cleanly.
4468 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08004469 if (c instanceof ContextImpl) {
4470 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004471 r.activity.getClass().getName(), "Activity");
4472 }
4473 }
4474 if (finishing) {
4475 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004476 ActivityManager.getService().activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004478 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 }
4480 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004481 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 }
4483
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004484 /**
4485 * @param preserveWindow Whether the activity should try to reuse the window it created,
4486 * including the decor view after the relaunch.
4487 */
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004488 public final void requestRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -08004489 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004490 int configChanges, boolean notResumed, Configuration config,
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004491 Configuration overrideConfig, boolean fromServer, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004492 ActivityClientRecord target = null;
4493
Craig Mautner88c05892013-06-28 09:47:45 -07004494 synchronized (mResourcesManager) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004495 for (int i=0; i<mRelaunchingActivities.size(); i++) {
4496 ActivityClientRecord r = mRelaunchingActivities.get(i);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004497 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004498 if (r.token == token) {
4499 target = r;
4500 if (pendingResults != null) {
4501 if (r.pendingResults != null) {
4502 r.pendingResults.addAll(pendingResults);
4503 } else {
4504 r.pendingResults = pendingResults;
4505 }
4506 }
4507 if (pendingNewIntents != null) {
4508 if (r.pendingIntents != null) {
4509 r.pendingIntents.addAll(pendingNewIntents);
4510 } else {
4511 r.pendingIntents = pendingNewIntents;
4512 }
4513 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004514
4515 // For each relaunch request, activity manager expects an answer
4516 if (!r.onlyLocalRequest && fromServer) {
4517 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004518 ActivityManager.getService().activityRelaunched(token);
Jorim Jaggife89d122015-12-22 16:28:44 +01004519 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004520 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01004521 }
4522 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004523 break;
4524 }
4525 }
4526
4527 if (target == null) {
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004528 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null, fromServer:"
4529 + fromServer);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004530 target = new ActivityClientRecord();
4531 target.token = token;
4532 target.pendingResults = pendingResults;
4533 target.pendingIntents = pendingNewIntents;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004534 target.mPreserveWindow = preserveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004535 if (!fromServer) {
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004536 final ActivityClientRecord existing = mActivities.get(token);
4537 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + existing);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004538 if (existing != null) {
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004539 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: paused= "
4540 + existing.paused);;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004541 target.startsNotResumed = existing.paused;
Wale Ogunwale93f543c2015-02-17 16:55:03 -08004542 target.overrideConfig = existing.overrideConfig;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004543 }
4544 target.onlyLocalRequest = true;
4545 }
4546 mRelaunchingActivities.add(target);
Jeff Brown9ef09972013-10-15 20:49:59 -07004547 sendMessage(H.RELAUNCH_ACTIVITY, target);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004548 }
4549
4550 if (fromServer) {
4551 target.startsNotResumed = notResumed;
4552 target.onlyLocalRequest = false;
4553 }
4554 if (config != null) {
4555 target.createdConfig = config;
4556 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08004557 if (overrideConfig != null) {
4558 target.overrideConfig = overrideConfig;
4559 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004560 target.pendingConfigChanges |= configChanges;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004561 target.relaunchSeq = getLifecycleSeq();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004562 }
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004563 if (DEBUG_ORDER) Slog.d(TAG, "relaunchActivity " + ActivityThread.this + ", target "
4564 + target + " operation received seq: " + target.relaunchSeq);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004565 }
4566
Romain Guy65b345f2011-07-27 18:51:50 -07004567 private void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 // If we are getting ready to gc after going to the background, well
4569 // we are back active so skip it.
4570 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004571 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572
4573 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004574 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07004575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 // First: make sure we have the most recent configuration and most
4577 // recent version of the activity, or skip it if some previous call
4578 // had taken a more recent version.
Craig Mautner88c05892013-06-28 09:47:45 -07004579 synchronized (mResourcesManager) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 int N = mRelaunchingActivities.size();
4581 IBinder token = tmp.token;
4582 tmp = null;
4583 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004584 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 if (r.token == token) {
4586 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004587 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 mRelaunchingActivities.remove(i);
4589 i--;
4590 N--;
4591 }
4592 }
Bob Leee5408332009-09-04 18:31:17 -07004593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004595 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 return;
4597 }
Bob Leee5408332009-09-04 18:31:17 -07004598
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004599 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
4600 + tmp.token + " with configChanges=0x"
4601 + Integer.toHexString(configChanges));
4602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 if (mPendingConfiguration != null) {
4604 changedConfig = mPendingConfiguration;
4605 mPendingConfiguration = null;
4606 }
4607 }
Bob Leee5408332009-09-04 18:31:17 -07004608
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004609 if (tmp.lastProcessedSeq > tmp.relaunchSeq) {
4610 Slog.wtf(TAG, "For some reason target: " + tmp + " has lower sequence: "
4611 + tmp.relaunchSeq + " than current sequence: " + tmp.lastProcessedSeq);
4612 } else {
4613 tmp.lastProcessedSeq = tmp.relaunchSeq;
4614 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004615 if (tmp.createdConfig != null) {
4616 // If the activity manager is passing us its current config,
4617 // assume that is really what we want regardless of what we
4618 // may have pending.
4619 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004620 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
4621 && mConfiguration.diff(tmp.createdConfig) != 0)) {
4622 if (changedConfig == null
4623 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
4624 changedConfig = tmp.createdConfig;
4625 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004626 }
4627 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004628
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004629 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004630 + tmp.token + ": changedConfig=" + changedConfig);
Tim Murraye1e6c662015-04-07 13:24:14 -07004631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 // If there was a pending configuration change, execute it first.
4633 if (changedConfig != null) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -07004634 mCurDefaultDisplayDpi = changedConfig.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07004635 updateDefaultDensity();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004636 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 }
Bob Leee5408332009-09-04 18:31:17 -07004638
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004639 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004640 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 if (r == null) {
Jorim Jaggife89d122015-12-22 16:28:44 +01004642 if (!tmp.onlyLocalRequest) {
4643 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004644 ActivityManager.getService().activityRelaunched(tmp.token);
Jorim Jaggife89d122015-12-22 16:28:44 +01004645 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004646 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01004647 }
4648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 return;
4650 }
Bob Leee5408332009-09-04 18:31:17 -07004651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004653 r.onlyLocalRequest = tmp.onlyLocalRequest;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004654 r.mPreserveWindow = tmp.mPreserveWindow;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004655 r.lastProcessedSeq = tmp.lastProcessedSeq;
4656 r.relaunchSeq = tmp.relaunchSeq;
Christopher Tateb70f3df2009-04-07 16:07:59 -07004657 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07004658
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004659 r.activity.mChangingConfigurations = true;
4660
Robert Carr23fa16b2016-01-13 13:19:58 -08004661 // If we are preserving the main window across relaunches we would also like to preserve
4662 // the children. However the client side view system does not support preserving
4663 // the child views so we notify the window manager to expect these windows to
4664 // be replaced and defer requests to destroy or hide them. This way we can achieve
4665 // visual continuity. It's important that we do this here prior to pause and destroy
4666 // as that is when we may hide or remove the child views.
Robert Carr77bdfb52016-05-02 18:18:31 -07004667 //
4668 // There is another scenario, if we have decided locally to relaunch the app from a
4669 // call to recreate, then none of the windows will be prepared for replacement or
4670 // preserved by the server, so we want to notify it that we are preparing to replace
4671 // everything
Robert Carr23fa16b2016-01-13 13:19:58 -08004672 try {
Robert Carr77bdfb52016-05-02 18:18:31 -07004673 if (r.mPreserveWindow || r.onlyLocalRequest) {
4674 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
4675 r.token, !r.onlyLocalRequest);
Robert Carr23fa16b2016-01-13 13:19:58 -08004676 }
4677 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004678 throw e.rethrowFromSystemServer();
Robert Carr23fa16b2016-01-13 13:19:58 -08004679 }
4680
Dianne Hackborne2b04802010-12-09 09:24:55 -08004681 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 if (!r.paused) {
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004683 performPauseActivity(r.token, false, r.isPreHoneycomb(), "handleRelaunchActivity");
Dianne Hackborne2b04802010-12-09 09:24:55 -08004684 }
4685 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
Craig Mautnera0026042014-04-23 11:45:37 -07004686 callCallActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 }
Bob Leee5408332009-09-04 18:31:17 -07004688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07004690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 r.activity = null;
4692 r.window = null;
4693 r.hideForNow = false;
4694 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07004695 // Merge any pending results and pending intents; don't just replace them
4696 if (tmp.pendingResults != null) {
4697 if (r.pendingResults == null) {
4698 r.pendingResults = tmp.pendingResults;
4699 } else {
4700 r.pendingResults.addAll(tmp.pendingResults);
4701 }
4702 }
4703 if (tmp.pendingIntents != null) {
4704 if (r.pendingIntents == null) {
4705 r.pendingIntents = tmp.pendingIntents;
4706 } else {
4707 r.pendingIntents.addAll(tmp.pendingIntents);
4708 }
4709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004710 r.startsNotResumed = tmp.startsNotResumed;
Wale Ogunwale60454db2015-01-23 16:05:07 -08004711 r.overrideConfig = tmp.overrideConfig;
Bob Leee5408332009-09-04 18:31:17 -07004712
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004713 handleLaunchActivity(r, currentIntent, "handleRelaunchActivity");
Jorim Jaggife89d122015-12-22 16:28:44 +01004714
4715 if (!tmp.onlyLocalRequest) {
4716 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004717 ActivityManager.getService().activityRelaunched(r.token);
Jorim Jaggi4846ee32016-01-07 17:39:12 +01004718 if (r.window != null) {
4719 r.window.reportActivityRelaunched();
4720 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004721 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004722 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01004723 }
4724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004725 }
4726
Craig Mautnera0026042014-04-23 11:45:37 -07004727 private void callCallActivityOnSaveInstanceState(ActivityClientRecord r) {
4728 r.state = new Bundle();
4729 r.state.setAllowFds(false);
4730 if (r.isPersistable()) {
4731 r.persistentState = new PersistableBundle();
4732 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
4733 r.persistentState);
4734 } else {
4735 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
4736 }
4737 }
4738
Dianne Hackborn73c14162012-09-19 15:45:06 -07004739 ArrayList<ComponentCallbacks2> collectComponentCallbacks(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004741 ArrayList<ComponentCallbacks2> callbacks
4742 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07004743
Craig Mautner88c05892013-06-28 09:47:45 -07004744 synchronized (mResourcesManager) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004745 final int NAPP = mAllApplications.size();
4746 for (int i=0; i<NAPP; i++) {
Dianne Hackborn73c14162012-09-19 15:45:06 -07004747 callbacks.add(mAllApplications.get(i));
4748 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004749 final int NACT = mActivities.size();
4750 for (int i=0; i<NACT; i++) {
4751 ActivityClientRecord ar = mActivities.valueAt(i);
4752 Activity a = ar.activity;
4753 if (a != null) {
4754 Configuration thisConfig = applyConfigCompatMainThread(
4755 mCurDefaultDisplayDpi, newConfig,
4756 ar.packageInfo.getCompatibilityInfo());
4757 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
4758 // If the activity is currently resumed, its configuration
4759 // needs to change right now.
4760 callbacks.add(a);
4761 } else if (thisConfig != null) {
4762 // Otherwise, we will tell it about the change
4763 // the next time it is resumed or shown. Note that
4764 // the activity manager may, before then, decide the
4765 // activity needs to be destroyed to handle its new
4766 // configuration.
4767 if (DEBUG_CONFIGURATION) {
4768 Slog.v(TAG, "Setting activity "
4769 + ar.activityInfo.name + " newConfig=" + thisConfig);
Romain Guya998dff2012-03-23 18:58:36 -07004770 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004771 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004772 }
4773 }
4774 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004775 final int NSVC = mServices.size();
4776 for (int i=0; i<NSVC; i++) {
4777 callbacks.add(mServices.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004778 }
4779 }
4780 synchronized (mProviderMap) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004781 final int NPRV = mLocalProviders.size();
4782 for (int i=0; i<NPRV; i++) {
4783 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004784 }
4785 }
Bob Leee5408332009-09-04 18:31:17 -07004786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004787 return callbacks;
4788 }
Bob Leee5408332009-09-04 18:31:17 -07004789
Adam Lesinski082614c2016-03-04 14:33:47 -08004790 /**
4791 * Updates the configuration for an Activity. The ActivityClientRecord's
4792 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
4793 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
4794 * the updated Configuration.
4795 * @param r ActivityClientRecord representing the Activity.
4796 * @param newBaseConfig The new configuration to use. This may be augmented with
4797 * {@link ActivityClientRecord#overrideConfig}.
Adam Lesinski082614c2016-03-04 14:33:47 -08004798 */
4799 private void performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004800 Configuration newBaseConfig) {
4801 performConfigurationChangedForActivity(r, newBaseConfig,
4802 r.activity.getDisplay().getDisplayId(), false /* movedToDifferentDisplay */);
4803 }
4804
4805 /**
4806 * Updates the configuration for an Activity. The ActivityClientRecord's
4807 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
4808 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
4809 * the updated Configuration.
4810 * @param r ActivityClientRecord representing the Activity.
4811 * @param newBaseConfig The new configuration to use. This may be augmented with
4812 * {@link ActivityClientRecord#overrideConfig}.
4813 * @param displayId The id of the display where the Activity currently resides.
4814 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004815 * @return {@link Configuration} instance sent to client, null if not sent.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004816 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004817 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004818 Configuration newBaseConfig, int displayId, boolean movedToDifferentDisplay) {
Adam Lesinski082614c2016-03-04 14:33:47 -08004819 r.tmpConfig.setTo(newBaseConfig);
4820 if (r.overrideConfig != null) {
4821 r.tmpConfig.updateFrom(r.overrideConfig);
4822 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004823 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
4824 r.tmpConfig, r.overrideConfig, displayId, movedToDifferentDisplay);
Adam Lesinski082614c2016-03-04 14:33:47 -08004825 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004826 return reportedConfig;
Adam Lesinski082614c2016-03-04 14:33:47 -08004827 }
4828
4829 /**
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07004830 * Creates a new Configuration only if override would modify base. Otherwise returns base.
4831 * @param base The base configuration.
4832 * @param override The update to apply to the base configuration. Can be null.
4833 * @return A Configuration representing base with override applied.
4834 */
4835 private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
4836 @Nullable Configuration override) {
4837 if (override == null) {
4838 return base;
4839 }
4840 Configuration newConfig = new Configuration(base);
4841 newConfig.updateFrom(override);
4842 return newConfig;
4843 }
4844
4845 /**
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004846 * Decides whether to update a component's configuration and whether to inform it.
Adam Lesinski082614c2016-03-04 14:33:47 -08004847 * @param cb The component callback to notify of configuration change.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004848 * @param newConfig The new configuration.
4849 */
4850 private void performConfigurationChanged(ComponentCallbacks2 cb, Configuration newConfig) {
4851 if (!REPORT_TO_ACTIVITY) {
4852 return;
4853 }
4854
4855 // ContextThemeWrappers may override the configuration for that context. We must check and
4856 // apply any overrides defined.
4857 Configuration contextThemeWrapperOverrideConfig = null;
4858 if (cb instanceof ContextThemeWrapper) {
4859 final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
4860 contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
4861 }
4862
4863 // Apply the ContextThemeWrapper override if necessary.
4864 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
4865 // in many places.
4866 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
4867 newConfig, contextThemeWrapperOverrideConfig);
4868 cb.onConfigurationChanged(configToReport);
4869 }
4870
4871 /**
4872 * Decides whether to update an Activity's configuration and whether to inform it.
4873 * @param activity The activity to notify of configuration change.
Adam Lesinski082614c2016-03-04 14:33:47 -08004874 * @param newConfig The new configuration.
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07004875 * @param amOverrideConfig The override config that differentiates the Activity's configuration
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004876 * from the base global configuration. This is supplied by
4877 * ActivityManager.
4878 * @param displayId Id of the display where activity currently resides.
4879 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004880 * @return Configuration sent to client, null if no changes and not moved to different display.
Adam Lesinski082614c2016-03-04 14:33:47 -08004881 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004882 private Configuration performActivityConfigurationChanged(Activity activity,
4883 Configuration newConfig, Configuration amOverrideConfig, int displayId,
4884 boolean movedToDifferentDisplay) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004885 if (activity == null) {
4886 throw new IllegalArgumentException("No activity provided.");
4887 }
4888 final IBinder activityToken = activity.getActivityToken();
4889 if (activityToken == null) {
4890 throw new IllegalArgumentException("Activity token not set. Is the activity attached?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 }
Bob Leee5408332009-09-04 18:31:17 -07004892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 boolean shouldChangeConfig = false;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004894 if (activity.mCurrentConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 shouldChangeConfig = true;
4896 } else {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004897 // If the new config is the same as the config this Activity is already running with and
4898 // the override config also didn't change, then don't bother calling
4899 // onConfigurationChanged.
Bryce Lee658d9842017-07-28 08:33:36 -07004900 final int diff = activity.mCurrentConfig.diffPublicOnly(newConfig);
4901
Andrii Kulian3b3c9142016-07-18 19:15:56 -07004902 if (diff != 0 || !mResourcesManager.isSameResourcesOverrideConfig(activityToken,
4903 amOverrideConfig)) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07004904 // Always send the task-level config changes. For system-level configuration, if
4905 // this activity doesn't handle any of the config changes, then don't bother
4906 // calling onConfigurationChanged as we're going to destroy it.
4907 if (!mUpdatingSystemConfig
4908 || (~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004909 || !REPORT_TO_ACTIVITY) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07004910 shouldChangeConfig = true;
4911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004912 }
4913 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004914 if (!shouldChangeConfig && !movedToDifferentDisplay) {
4915 // Nothing significant, don't proceed with updating and reporting.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004916 return null;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004917 }
4918
4919 // Propagate the configuration change to ResourcesManager and Activity.
4920
4921 // ContextThemeWrappers may override the configuration for that context. We must check and
4922 // apply any overrides defined.
4923 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
4924
4925 // We only update an Activity's configuration if this is not a global configuration change.
4926 // This must also be done before the callback, or else we violate the contract that the new
4927 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
4928 // Also apply the ContextThemeWrapper override if necessary.
4929 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
4930 // many places.
4931 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
4932 amOverrideConfig, contextThemeWrapperOverrideConfig);
4933 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig,
4934 displayId, movedToDifferentDisplay);
4935
4936 activity.mConfigChangeFlags = 0;
4937 activity.mCurrentConfig = new Configuration(newConfig);
4938
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004939 // Apply the ContextThemeWrapper override if necessary.
4940 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
4941 // in many places.
4942 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
4943 contextThemeWrapperOverrideConfig);
4944
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004945 if (!REPORT_TO_ACTIVITY) {
4946 // Not configured to report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004947 return configToReport;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004948 }
4949
4950 if (movedToDifferentDisplay) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004951 activity.dispatchMovedToDisplay(displayId, configToReport);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004952 }
Bob Leee5408332009-09-04 18:31:17 -07004953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 if (shouldChangeConfig) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004955 activity.mCalled = false;
4956 activity.onConfigurationChanged(configToReport);
4957 if (!activity.mCalled) {
4958 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
4959 " did not call through to super.onConfigurationChanged()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 }
4961 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004962
4963 return configToReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 }
4965
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07004966 public final void applyConfigurationToResources(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -07004967 synchronized (mResourcesManager) {
4968 mResourcesManager.applyConfigurationToResourcesLocked(config, null);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07004969 }
4970 }
4971
Dianne Hackborn908aecc2012-07-31 16:37:34 -07004972 final Configuration applyCompatConfiguration(int displayDensity) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07004973 Configuration config = mConfiguration;
4974 if (mCompatConfiguration == null) {
4975 mCompatConfiguration = new Configuration();
4976 }
4977 mCompatConfiguration.setTo(mConfiguration);
Adam Lesinski082614c2016-03-04 14:33:47 -08004978 if (mResourcesManager.applyCompatConfigurationLocked(displayDensity,
4979 mCompatConfiguration)) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07004980 config = mCompatConfiguration;
4981 }
4982 return config;
4983 }
4984
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004985 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004986
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07004987 int configDiff = 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004988
Bryce Lee658d9842017-07-28 08:33:36 -07004989 // This flag tracks whether the new configuration is fundamentally equivalent to the
4990 // existing configuration. This is necessary to determine whether non-activity
4991 // callbacks should receive notice when the only changes are related to non-public fields.
4992 // We do not gate calling {@link #performActivityConfigurationChanged} based on this flag
4993 // as that method uses the same check on the activity config override as well.
4994 final boolean equivalent = config != null && mConfiguration != null
4995 && (0 == mConfiguration.diffPublicOnly(config));
4996
Craig Mautner88c05892013-06-28 09:47:45 -07004997 synchronized (mResourcesManager) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004998 if (mPendingConfiguration != null) {
4999 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
5000 config = mPendingConfiguration;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005001 mCurDefaultDisplayDpi = config.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005002 updateDefaultDensity();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005003 }
5004 mPendingConfiguration = null;
5005 }
5006
5007 if (config == null) {
5008 return;
5009 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005010
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005011 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005012 + config);
Craig Mautner88c05892013-06-28 09:47:45 -07005013
5014 mResourcesManager.applyConfigurationToResourcesLocked(config, compat);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005015 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
5016 mResourcesManager.getConfiguration().getLocales());
Craig Mautner88c05892013-06-28 09:47:45 -07005017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 if (mConfiguration == null) {
5019 mConfiguration = new Configuration();
5020 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005021 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005022 return;
5023 }
Alan Viverettee54d2452015-05-06 10:41:43 -07005024
5025 configDiff = mConfiguration.updateFrom(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005026 config = applyCompatConfiguration(mCurDefaultDisplayDpi);
Alan Viverette395cd012015-08-11 17:27:04 -04005027
5028 final Theme systemTheme = getSystemContext().getTheme();
5029 if ((systemTheme.getChangingConfigurations() & configDiff) != 0) {
5030 systemTheme.rebase();
5031 }
Adam Lesinskia82b6262017-03-21 16:56:17 -07005032
5033 final Theme systemUiTheme = getSystemUiContext().getTheme();
5034 if ((systemUiTheme.getChangingConfigurations() & configDiff) != 0) {
5035 systemUiTheme.rebase();
5036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 }
Dianne Hackborn73c14162012-09-19 15:45:06 -07005038
5039 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(false, config);
5040
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005041 freeTextLayoutCachesIfNeeded(configDiff);
5042
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005043 if (callbacks != null) {
5044 final int N = callbacks.size();
5045 for (int i=0; i<N; i++) {
Andrii Kulian701214b2016-04-07 09:36:33 -07005046 ComponentCallbacks2 cb = callbacks.get(i);
5047 if (cb instanceof Activity) {
5048 // If callback is an Activity - call corresponding method to consider override
5049 // config and avoid onConfigurationChanged if it hasn't changed.
5050 Activity a = (Activity) cb;
5051 performConfigurationChangedForActivity(mActivities.get(a.getActivityToken()),
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005052 config);
Bryce Lee658d9842017-07-28 08:33:36 -07005053 } else if (!equivalent) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005054 performConfigurationChanged(cb, config);
Andrii Kulian701214b2016-04-07 09:36:33 -07005055 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 }
5058 }
5059
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005060 void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
Adam Lesinskid33ef562017-01-19 14:49:59 -08005061 // Updates triggered by package installation go through a package update
5062 // receiver. Here we try to capture ApplicationInfo changes that are
5063 // caused by other sources, such as overlays. That means we want to be as conservative
5064 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
5065 // to see if anything needs to change.
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005066 LoadedApk apk;
5067 LoadedApk resApk;
5068 // Update all affected loaded packages with new package information
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005069 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005070 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005071 apk = ref != null ? ref.get() : null;
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005072 ref = mResourcePackages.get(ai.packageName);
5073 resApk = ref != null ? ref.get() : null;
5074 }
5075 if (apk != null) {
5076 final ArrayList<String> oldPaths = new ArrayList<>();
5077 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
5078 apk.updateApplicationInfo(ai, oldPaths);
5079 }
5080 if (resApk != null) {
5081 final ArrayList<String> oldPaths = new ArrayList<>();
5082 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
5083 resApk.updateApplicationInfo(ai, oldPaths);
5084 }
5085 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005086 // Update all affected Resources objects to use new ResourcesImpl
5087 mResourcesManager.applyNewResourceDirsLocked(ai.sourceDir, ai.resourceDirs);
5088 }
5089
5090 ApplicationPackageManager.configurationChanged();
5091
5092 // Trigger a regular Configuration change event, only with a different assetsSeq number
5093 // so that we actually call through to all components.
Adam Lesinskia82b6262017-03-21 16:56:17 -07005094 // TODO(adamlesinski): Change this to make use of ActivityManager's upcoming ability to
5095 // store configurations per-process.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005096 Configuration newConfig = new Configuration();
Adam Lesinskia82b6262017-03-21 16:56:17 -07005097 newConfig.assetsSeq = (mConfiguration != null ? mConfiguration.assetsSeq : 0) + 1;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005098 handleConfigurationChanged(newConfig, null);
5099
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07005100 requestRelaunchAllActivities();
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005101 }
5102
Romain Guy46bfc482013-08-16 18:38:29 -07005103 static void freeTextLayoutCachesIfNeeded(int configDiff) {
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005104 if (configDiff != 0) {
5105 // Ask text layout engine to free its caches if there is a locale change
5106 boolean hasLocaleConfigChange = ((configDiff & ActivityInfo.CONFIG_LOCALE) != 0);
5107 if (hasLocaleConfigChange) {
5108 Canvas.freeTextLayoutCaches();
5109 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Cleared TextLayout Caches");
5110 }
5111 }
5112 }
5113
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005114 /**
5115 * Handle new activity configuration and/or move to a different display.
5116 * @param data Configuration update data.
5117 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
5118 * value didn't change.
5119 */
Andrii Kulian44607962017-03-16 11:06:24 -07005120 void handleActivityConfigurationChanged(ActivityConfigChangeData data, int displayId) {
Wale Ogunwalec2607b42015-02-07 16:16:59 -08005121 ActivityClientRecord r = mActivities.get(data.activityToken);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005122 // Check input params.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 if (r == null || r.activity == null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005124 if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 return;
5126 }
Andrii Kulian51c1b672017-04-07 18:39:32 -07005127 final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
5128 && displayId != r.activity.getDisplay().getDisplayId();
Bob Leee5408332009-09-04 18:31:17 -07005129
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005130 // Perform updates.
Adam Lesinski082614c2016-03-04 14:33:47 -08005131 r.overrideConfig = data.overrideConfig;
Stephen Kiazykf903b732017-03-20 16:23:45 -07005132 final ViewRootImpl viewRoot = r.activity.mDecor != null
5133 ? r.activity.mDecor.getViewRootImpl() : null;
5134
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005135 if (movedToDifferentDisplay) {
5136 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity moved to display, activity:"
5137 + r.activityInfo.name + ", displayId=" + displayId
5138 + ", config=" + data.overrideConfig);
5139
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005140 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
5141 mCompatConfiguration, displayId, true /* movedToDifferentDisplay */);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005142 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005143 viewRoot.onMovedToDisplay(displayId, reportedConfig);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005144 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005145 } else {
5146 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
5147 + r.activityInfo.name + ", config=" + data.overrideConfig);
5148 performConfigurationChangedForActivity(r, mCompatConfiguration);
5149 }
Andrii Kulian44607962017-03-16 11:06:24 -07005150 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
5151 // update to make sure that resources are updated before updating itself.
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005152 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005153 viewRoot.updateConfiguration(displayId);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005154 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005155 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 }
5157
Jeff Hao1b012d32014-08-20 10:35:34 -07005158 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005159 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005160 try {
Romain Guy7eabe552011-07-21 14:56:34 -07005161 switch (profileType) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005162 default:
5163 mProfiler.setProfiler(profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005164 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005165 break;
5166 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005167 } catch (RuntimeException e) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005168 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005169 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07005170 } finally {
Andreas Gampe2b073a02017-06-22 17:28:57 -07005171 profilerInfo.closeFd();
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005172 }
5173 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07005174 switch (profileType) {
Romain Guy7eabe552011-07-21 14:56:34 -07005175 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005176 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005177 break;
Romain Guy7eabe552011-07-21 14:56:34 -07005178 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005179 }
5180 }
Bob Leee5408332009-09-04 18:31:17 -07005181
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005182 /**
5183 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
5184 * so that profiler data won't be lost.
5185 *
5186 * @hide
5187 */
5188 public void stopProfiling() {
Amith Yamasanib1684432017-01-26 14:57:20 -08005189 if (mProfiler != null) {
5190 mProfiler.stopProfiling();
5191 }
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005192 }
5193
Christopher Ferris8d652f82017-04-11 16:29:18 -07005194 static void handleDumpHeap(DumpHeapData dhd) {
Makoto Onuki4556b7b2017-07-07 14:58:58 -07005195 if (dhd.runGc) {
5196 System.gc();
5197 System.runFinalization();
5198 System.gc();
5199 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005200 if (dhd.managed) {
Andy McFadden824c5102010-07-09 16:26:57 -07005201 try {
5202 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
5203 } catch (IOException e) {
5204 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
5205 + " -- can the process access this path?");
5206 } finally {
5207 try {
5208 dhd.fd.close();
5209 } catch (IOException e) {
5210 Slog.w(TAG, "Failure closing profile fd", e);
5211 }
5212 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005213 } else if (dhd.mallocInfo) {
5214 Debug.dumpNativeMallocInfo(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005215 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07005216 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005217 }
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005218 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005219 ActivityManager.getService().dumpHeapFinished(dhd.path);
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005220 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005221 throw e.rethrowFromSystemServer();
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005222 }
Andy McFadden824c5102010-07-09 16:26:57 -07005223 }
5224
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005225 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
5226 boolean hasPkgInfo = false;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005227 switch (cmd) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005228 case ApplicationThreadConstants.PACKAGE_REMOVED:
5229 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005230 {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005231 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005232 if (packages == null) {
5233 break;
5234 }
5235 synchronized (mResourcesManager) {
5236 for (int i = packages.length - 1; i >= 0; i--) {
5237 if (!hasPkgInfo) {
5238 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
5239 if (ref != null && ref.get() != null) {
5240 hasPkgInfo = true;
5241 } else {
5242 ref = mResourcePackages.get(packages[i]);
5243 if (ref != null && ref.get() != null) {
5244 hasPkgInfo = true;
5245 }
5246 }
5247 }
5248 if (killApp) {
5249 mPackages.remove(packages[i]);
5250 mResourcePackages.remove(packages[i]);
5251 }
5252 }
5253 }
5254 break;
5255 }
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005256 case ApplicationThreadConstants.PACKAGE_REPLACED:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005257 {
5258 if (packages == null) {
5259 break;
5260 }
5261 synchronized (mResourcesManager) {
5262 for (int i = packages.length - 1; i >= 0; i--) {
5263 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
5264 LoadedApk pkgInfo = ref != null ? ref.get() : null;
5265 if (pkgInfo != null) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005266 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005267 } else {
5268 ref = mResourcePackages.get(packages[i]);
Todd Kennedy39bfee52016-02-24 10:28:21 -08005269 pkgInfo = ref != null ? ref.get() : null;
5270 if (pkgInfo != null) {
mark_chen89764e32014-12-12 15:38:48 +08005271 hasPkgInfo = true;
5272 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005273 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005274 // If the package is being replaced, yet it still has a valid
5275 // LoadedApk object, the package was updated with _DONT_KILL.
5276 // Adjust it's internal references to the application info and
5277 // resources.
5278 if (pkgInfo != null) {
5279 try {
5280 final String packageName = packages[i];
5281 final ApplicationInfo aInfo =
5282 sPackageManager.getApplicationInfo(
5283 packageName,
5284 0 /*flags*/,
5285 UserHandle.myUserId());
5286
5287 if (mActivities.size() > 0) {
5288 for (ActivityClientRecord ar : mActivities.values()) {
5289 if (ar.activityInfo.applicationInfo.packageName
5290 .equals(packageName)) {
5291 ar.activityInfo.applicationInfo = aInfo;
5292 ar.packageInfo = pkgInfo;
5293 }
5294 }
5295 }
5296 final List<String> oldPaths =
5297 sPackageManager.getPreviousCodePaths(packageName);
5298 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
5299 } catch (RemoteException e) {
5300 }
5301 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005302 }
5303 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005304 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005305 }
5306 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005307 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005308 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005310 final void handleLowMemory() {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005311 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Bob Leee5408332009-09-04 18:31:17 -07005312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 final int N = callbacks.size();
5314 for (int i=0; i<N; i++) {
5315 callbacks.get(i).onLowMemory();
5316 }
5317
Chris Tatece229052009-03-25 16:44:52 -07005318 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
5319 if (Process.myUid() != Process.SYSTEM_UID) {
5320 int sqliteReleased = SQLiteDatabase.releaseMemory();
5321 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
5322 }
Bob Leee5408332009-09-04 18:31:17 -07005323
Mike Reedcaf0df12009-04-27 14:32:05 -04005324 // Ask graphics to free up as much as possible (font/image caches)
5325 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005326
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005327 // Ask text layout engine to free also as much as possible
5328 Canvas.freeTextLayoutCaches();
5329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005330 BinderInternal.forceGc("mem");
5331 }
5332
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005333 final void handleTrimMemory(int level) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07005334 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005335
Dianne Hackborn73c14162012-09-19 15:45:06 -07005336 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005337
5338 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07005339 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005340 callbacks.get(i).onTrimMemory(level);
5341 }
Romain Guy19f86e82012-04-23 15:19:07 -07005342
John Reckf47a5942014-06-30 16:20:04 -07005343 WindowManagerGlobal.getInstance().trimMemory(level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005344 }
5345
Jesse Hall317fa5a2017-05-23 15:46:55 -07005346 private void setupGraphicsSupport(Context context) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005347 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
Romain Guya9582652011-11-10 14:20:10 -08005348
Jesse Hall317fa5a2017-05-23 15:46:55 -07005349 // The system package doesn't have real data directories, so don't set up cache paths.
5350 if (!"android".equals(context.getPackageName())) {
5351 // This cache location probably points at credential-encrypted
5352 // storage which may not be accessible yet; assign it anyway instead
5353 // of pointing at device-encrypted storage.
5354 final File cacheDir = context.getCacheDir();
5355 if (cacheDir != null) {
5356 // Provide a usable directory for temporary files
5357 System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
5358 } else {
5359 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
5360 + "due to missing cache directory");
Romain Guya9582652011-11-10 14:20:10 -08005361 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005362
5363 // Setup a location to store generated/compiled graphics code.
5364 final Context deviceContext = context.createDeviceProtectedStorageContext();
5365 final File codeCacheDir = deviceContext.getCodeCacheDir();
5366 if (codeCacheDir != null) {
5367 try {
5368 int uid = Process.myUid();
5369 String[] packages = getPackageManager().getPackagesForUid(uid);
5370 if (packages != null) {
Romain Guycecbe072017-07-18 15:42:06 -07005371 ThreadedRenderer.setupDiskCache(codeCacheDir);
5372 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005373 }
5374 } catch (RemoteException e) {
5375 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5376 throw e.rethrowFromSystemServer();
5377 }
5378 } else {
5379 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
5380 }
Romain Guya9582652011-11-10 14:20:10 -08005381 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005382
Jesse Hallc37984f2017-05-23 16:55:08 -07005383 GraphicsEnvironment.chooseDriver(context);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005384 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005385 }
5386
5387 private void updateDefaultDensity() {
Alan Viverette2ac46f12016-02-04 16:58:14 -05005388 final int densityDpi = mCurDefaultDisplayDpi;
5389 if (!mDensityCompatMode
5390 && densityDpi != Configuration.DENSITY_DPI_UNDEFINED
5391 && densityDpi != DisplayMetrics.DENSITY_DEVICE) {
5392 DisplayMetrics.DENSITY_DEVICE = densityDpi;
5393 Bitmap.setDefaultDensity(densityDpi);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005394 }
5395 }
5396
Todd Kennedye713efc2016-05-10 13:45:40 -07005397 /**
5398 * Returns the correct library directory for the current ABI.
5399 * <p>
5400 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
5401 * libraries, we might need to choose the secondary depending on what the current
5402 * runtime's instruction set is.
5403 */
5404 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
5405 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null) {
5406 // Get the instruction set supported by the secondary ABI. In the presence
5407 // of a native bridge this might be different than the one secondary ABI used.
5408 String secondaryIsa =
5409 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
5410 final String secondaryDexCodeIsa =
5411 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
5412 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
5413
5414 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
5415 if (runtimeIsa.equals(secondaryIsa)) {
5416 return insInfo.secondaryNativeLibraryDir;
5417 }
5418 }
5419 return insInfo.nativeLibraryDir;
5420 }
5421
Adam Lesinskib61e4052016-05-19 18:23:05 -07005422 /**
5423 * The LocaleList set for the app's resources may have been shuffled so that the preferred
5424 * Locale is at position 0. We must find the index of this preferred Locale in the
5425 * original LocaleList.
5426 */
5427 private void updateLocaleListFromAppContext(Context context, LocaleList newLocaleList) {
5428 final Locale bestLocale = context.getResources().getConfiguration().getLocales().get(0);
5429 final int newLocaleListSize = newLocaleList.size();
5430 for (int i = 0; i < newLocaleListSize; i++) {
5431 if (bestLocale.equals(newLocaleList.get(i))) {
5432 LocaleList.setDefault(newLocaleList, i);
5433 return;
5434 }
5435 }
Adam Lesinski27d30162016-05-25 16:45:14 -07005436
5437 // The app may have overridden the LocaleList with its own Locale
5438 // (not present in the available list). Push the chosen Locale
5439 // to the front of the list.
5440 LocaleList.setDefault(new LocaleList(bestLocale, newLocaleList));
Adam Lesinskib61e4052016-05-19 18:23:05 -07005441 }
5442
Romain Guy65b345f2011-07-27 18:51:50 -07005443 private void handleBindApplication(AppBindData data) {
Calin Juravle8f5770d2016-04-12 14:12:04 +01005444 // Register the UI Thread as a sensitive thread to the runtime.
5445 VMRuntime.registerSensitiveThread();
Man Caocfa78b22015-06-11 20:14:34 -07005446 if (data.trackAllocation) {
5447 DdmVmInternal.enableRecentAllocations(true);
5448 }
5449
Dianne Hackbornd98885c2016-03-01 17:13:03 -08005450 // Note when this process has started.
5451 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
5452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 mBoundApplication = data;
5454 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07005455 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005457 mProfiler = new Profiler();
Jeff Hao1b012d32014-08-20 10:35:34 -07005458 if (data.initProfilerInfo != null) {
5459 mProfiler.profileFile = data.initProfilerInfo.profileFile;
5460 mProfiler.profileFd = data.initProfilerInfo.profileFd;
5461 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
5462 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -08005463 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
Jeff Hao1b012d32014-08-20 10:35:34 -07005464 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08005467 Process.setArgV0(data.processName);
Siva Velusamyd693dfa2012-09-10 14:36:58 -07005468 android.ddm.DdmHandleAppName.setAppName(data.processName,
5469 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005471 if (mProfiler.profileFd != null) {
5472 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07005473 }
5474
Joe Onoratod630f102011-03-17 18:42:26 -07005475 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
5476 // implementation to use the pool executor. Normally, we use the
5477 // serialized executor as the default. This has to happen in the
5478 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07005479 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07005480 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
5481 }
5482
Dianne Hackborn7895bc22014-09-05 15:09:03 -07005483 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
5484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 /*
5486 * Before spawning a new process, reset the time zone to be the system time zone.
5487 * This needs to be done because the system time zone could have changed after the
5488 * the spawning of this process. Without doing this this process would have the incorrect
5489 * system time zone.
5490 */
5491 TimeZone.setDefault(null);
5492
Adam Lesinskib61e4052016-05-19 18:23:05 -07005493 /*
5494 * Set the LocaleList. This may change once we create the App Context.
5495 */
5496 LocaleList.setDefault(data.config.getLocales());
5497
5498 synchronized (mResourcesManager) {
5499 /*
5500 * Update the system configuration since its preloaded and might not
5501 * reflect configuration changes. The configuration object passed
5502 * in AppBindData can be safely assumed to be up to date
5503 */
5504 mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
5505 mCurDefaultDisplayDpi = data.config.densityDpi;
5506
5507 // This calls mResourcesManager so keep it within the synchronized block.
5508 applyCompatConfiguration(mCurDefaultDisplayDpi);
5509 }
5510
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005511 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512
Dianne Hackborndde331c2012-08-03 14:01:57 -07005513 /**
5514 * Switch this process to density compatibility mode if needed.
5515 */
5516 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
5517 == 0) {
5518 mDensityCompatMode = true;
5519 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
5520 }
5521 updateDefaultDensity();
5522
Neil Fullerc66ec402016-11-14 16:06:42 +00005523 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
5524 Boolean is24Hr = null;
5525 if (use24HourSetting != null) {
5526 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
5527 }
5528 // null : use locale default for 12/24 hour formatting,
5529 // false : use 12 hour format,
5530 // true : use 24 hour format.
Narayan Kamathccb2a0862013-12-19 14:49:36 +00005531 DateFormat.set24HourTimePref(is24Hr);
5532
Jon Miranda836c0a82014-08-11 12:32:26 -07005533 View.mDebugViewAttributes =
5534 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
5535
Dianne Hackborn96e240f2009-07-26 17:42:30 -07005536 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07005537 * For system applications on userdebug/eng builds, log stack
5538 * traces of disk and network access to dropbox for analysis.
5539 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07005540 if ((data.appInfo.flags &
5541 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07005542 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
5543 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07005544 }
5545
5546 /**
Jeff Sharkey344744b2016-01-28 19:03:30 -07005547 * For apps targetting Honeycomb or later, we don't allow network usage
5548 * on the main event loop / UI thread. This is what ultimately throws
5549 * {@link NetworkOnMainThreadException}.
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07005550 */
Jeff Sharkey344744b2016-01-28 19:03:30 -07005551 if (data.appInfo.targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07005552 StrictMode.enableDeathOnNetwork();
5553 }
5554
Jeff Sharkey344744b2016-01-28 19:03:30 -07005555 /**
5556 * For apps targetting N or later, we don't allow file:// Uri exposure.
5557 * This is what ultimately throws {@link FileUriExposedException}.
5558 */
5559 if (data.appInfo.targetSdkVersion >= Build.VERSION_CODES.N) {
Thierry Strudele60b28d2016-02-25 02:14:16 +00005560 StrictMode.enableDeathOnFileUriExposure();
Jeff Sharkey344744b2016-01-28 19:03:30 -07005561 }
5562
Svet Ganov37e43272016-09-09 16:01:32 -07005563 // We deprecated Build.SERIAL and only apps that target pre NMR1
5564 // SDK can see it. Since access to the serial is now behind a
5565 // permission we push down the value and here we fix it up
5566 // before any app code has been loaded.
5567 try {
5568 Field field = Build.class.getDeclaredField("SERIAL");
5569 field.setAccessible(true);
5570 field.set(Build.class, data.buildSerial);
5571 } catch (NoSuchFieldException | IllegalAccessException e) {
5572 /* ignore */
5573 }
5574
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005575 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 // XXX should have option to change the port.
5577 Debug.changeDebugPort(8100);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005578 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005579 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 + " is waiting for the debugger on port 8100...");
5581
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005582 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 try {
5584 mgr.showWaitingForDebugger(mAppThread, true);
5585 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005586 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 }
5588
5589 Debug.waitForDebugger();
5590
5591 try {
5592 mgr.showWaitingForDebugger(mAppThread, false);
5593 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005594 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 }
5596
5597 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005598 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 + " can be debugged on port 8100...");
5600 }
5601 }
5602
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005603 // Allow application-generated systrace messages if we're debuggable.
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04005604 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
5605 Trace.setAppTracingAllowed(isAppDebuggable);
5606 if (isAppDebuggable && data.enableBinderTracking) {
5607 Binder.enableTracing();
5608 }
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005609
Robert Greenwalt434203a2010-10-11 16:00:27 -07005610 /**
5611 * Initialize the default http proxy in this process for the reasons we set the time zone.
5612 */
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005613 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
Alan Viverettebe64eae2015-09-03 14:56:04 -04005614 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005615 if (b != null) {
5616 // In pre-boot mode (doing initial launch to collect password), not
5617 // all system is up. This includes the connectivity service, so don't
5618 // crash if we can't get it.
Alan Viverettebe64eae2015-09-03 14:56:04 -04005619 final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005620 try {
Paul Jensencee9b512015-05-06 07:32:40 -04005621 final ProxyInfo proxyInfo = service.getProxyForNetwork(null);
Jason Monk207900c2014-04-25 15:00:09 -04005622 Proxy.setHttpProxySystemProperty(proxyInfo);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005623 } catch (RemoteException e) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005624 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005625 throw e.rethrowFromSystemServer();
5626 }
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005627 }
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005628 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Robert Greenwalt434203a2010-10-11 16:00:27 -07005629
Alan Viverette2107d692015-09-03 14:55:27 -04005630 // Instrumentation info affects the class loader, so load it before
5631 // setting up the app context.
5632 final InstrumentationInfo ii;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 if (data.instrumentationName != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 try {
Alan Viverette2107d692015-09-03 14:55:27 -04005635 ii = new ApplicationPackageManager(null, getPackageManager())
5636 .getInstrumentationInfo(data.instrumentationName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 } catch (PackageManager.NameNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 throw new RuntimeException(
Alan Viverette2107d692015-09-03 14:55:27 -04005639 "Unable to find instrumentation info for: " + data.instrumentationName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 }
5641
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005642 mInstrumentationPackageName = ii.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 mInstrumentationAppDir = ii.sourceDir;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005644 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
Todd Kennedye713efc2016-05-10 13:45:40 -07005645 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 mInstrumentedAppDir = data.info.getAppDir();
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005647 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
5648 mInstrumentedLibDir = data.info.getLibDir();
Alan Viverette2107d692015-09-03 14:55:27 -04005649 } else {
5650 ii = null;
5651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652
Alan Viverette2107d692015-09-03 14:55:27 -04005653 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005654 updateLocaleListFromAppContext(appContext,
5655 mResourcesManager.getConfiguration().getLocales());
Seigo Nonakac14dd782016-03-30 23:09:16 +09005656
Jesse Hall317fa5a2017-05-23 15:46:55 -07005657 if (!Process.isIsolated()) {
5658 setupGraphicsSupport(appContext);
Michael Lentine2ba303f2016-02-01 20:44:34 -06005659 }
Michael Lentine03d8f7682016-01-31 15:37:11 -06005660
Calin Juravle37dfc8e2017-03-13 19:02:32 -07005661 // If we use profiles, setup the dex reporter to notify package manager
5662 // of any relevant dex loads. The idle maintenance job will use the information
5663 // reported to optimize the loaded dex files.
5664 // Note that we only need one global reporter per app.
5665 // Make sure we do this before calling onCreate so that we can capture the
5666 // complete application startup.
5667 if (SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false)) {
Calin Juravlef5a7bfc2017-03-13 23:30:30 -07005668 BaseDexClassLoader.setReporter(DexLoadReporter.getInstance());
Calin Juravle37dfc8e2017-03-13 19:02:32 -07005669 }
5670
Chad Brubaker78d47122015-11-17 22:26:58 -08005671 // Install the Network Security Config Provider. This must happen before the application
5672 // code is loaded to prevent issues with instances of TLS objects being created before
5673 // the provider is installed.
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005674 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
Chad Brubaker276ee962016-06-08 12:57:46 -07005675 NetworkSecurityConfigProvider.install(appContext);
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005676 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Chad Brubaker78d47122015-11-17 22:26:58 -08005677
Alan Viverette2107d692015-09-03 14:55:27 -04005678 // Continue loading instrumentation.
5679 if (ii != null) {
Alan Viverette346296b2015-09-01 13:08:05 -04005680 final ApplicationInfo instrApp = new ApplicationInfo();
Jeff Sharkey15447792015-11-05 16:18:51 -08005681 ii.copyTo(instrApp);
Fyodor Kupolovaf38b8e2015-12-02 16:16:07 -08005682 instrApp.initForUser(UserHandle.myUserId());
Alan Viverettebe64eae2015-09-03 14:56:04 -04005683 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07005684 appContext.getClassLoader(), false, true, false);
Alan Viverettebe64eae2015-09-03 14:56:04 -04005685 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686
5687 try {
Alan Viverettebe64eae2015-09-03 14:56:04 -04005688 final ClassLoader cl = instrContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04005689 mInstrumentation = (Instrumentation)
5690 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 } catch (Exception e) {
5692 throw new RuntimeException(
5693 "Unable to instantiate instrumentation "
5694 + data.instrumentationName + ": " + e.toString(), e);
5695 }
5696
Alan Viverettebe64eae2015-09-03 14:56:04 -04005697 final ComponentName component = new ComponentName(ii.packageName, ii.name);
5698 mInstrumentation.init(this, instrContext, appContext, component,
5699 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005701 if (mProfiler.profileFile != null && !ii.handleProfiling
5702 && mProfiler.profileFd == null) {
5703 mProfiler.handlingProfiling = true;
Alan Viverettebe64eae2015-09-03 14:56:04 -04005704 final File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 file.getParentFile().mkdirs();
5706 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
5707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 } else {
5709 mInstrumentation = new Instrumentation();
5710 }
5711
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005712 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08005713 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Mathieu Chartier24cee072015-01-08 14:42:20 -08005714 } else {
5715 // Small heap, clamp to the current growth limit and let the heap release
5716 // pages after the growth limit to the non growth limit capacity. b/18387825
5717 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005718 }
5719
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005720 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08005721 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005722 // probably end up doing the same disk access.
Kurt Nelson5e154362017-06-29 17:20:56 -07005723 Application app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005724 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
Kurt Nelson571c3f62017-07-10 11:09:04 -07005725 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005727 // If the app is being launched for full backup or restore, bring it up in
5728 // a restricted environment with the base application class.
Kurt Nelson5e154362017-06-29 17:20:56 -07005729 app = data.info.makeApplication(data.restrictedBackupMode, null);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005730 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005731
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005732 // don't bring up providers in restricted mode; they may depend on the
5733 // app's custom Application class
5734 if (!data.restrictedBackupMode) {
Jeff Sharkey3e195892016-03-05 19:48:59 -07005735 if (!ArrayUtils.isEmpty(data.providers)) {
5736 installContentProviders(app, data.providers);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005737 // For process that contains content providers, we want to
5738 // ensure that the JIT is enabled "at some point".
5739 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
5740 }
5741 }
5742
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005743 // Do this after providers, since instrumentation tests generally start their
5744 // test thread at this point, and we don't want that racing.
5745 try {
5746 mInstrumentation.onCreate(data.instrumentationArgs);
5747 }
5748 catch (Exception e) {
5749 throw new RuntimeException(
5750 "Exception thrown in onCreate() of "
5751 + data.instrumentationName + ": " + e.toString(), e);
5752 }
Kurt Nelson571c3f62017-07-10 11:09:04 -07005753 try {
5754 mInstrumentation.callApplicationOnCreate(app);
5755 } catch (Exception e) {
5756 if (!mInstrumentation.onException(app, e)) {
5757 throw new RuntimeException(
5758 "Unable to create application " + app.getClass().getName()
5759 + ": " + e.toString(), e);
5760 }
5761 }
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005762 } finally {
Kurt Nelson571c3f62017-07-10 11:09:04 -07005763 // If the app targets < O-MR1, or doesn't change the thread policy
5764 // during startup, clobber the policy to maintain behavior of b/36951662
5765 if (data.appInfo.targetSdkVersion <= Build.VERSION_CODES.O
5766 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
5767 StrictMode.setThreadPolicy(savedPolicy);
Kurt Nelson5e154362017-06-29 17:20:56 -07005768 }
5769 }
5770
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005771 // Preload fonts resources
Seigo Nonaka54084b62017-04-24 14:46:23 -07005772 FontsContract.setApplicationContextForResources(appContext);
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005773 try {
5774 final ApplicationInfo info =
Amith Yamasani336d29d2017-02-14 15:14:09 -08005775 getPackageManager().getApplicationInfo(
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005776 data.appInfo.packageName,
5777 PackageManager.GET_META_DATA /*flags*/,
5778 UserHandle.myUserId());
5779 if (info.metaData != null) {
5780 final int preloadedFontsResource = info.metaData.getInt(
5781 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
5782 if (preloadedFontsResource != 0) {
5783 data.info.mResources.preloadFonts(preloadedFontsResource);
5784 }
5785 }
5786 } catch (RemoteException e) {
5787 throw e.rethrowFromSystemServer();
5788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 }
5790
5791 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005792 IActivityManager am = ActivityManager.getService();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005793 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
5794 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 Debug.stopMethodTracing();
5796 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005797 //Slog.i(TAG, "am: " + ActivityManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 // + ", app thr: " + mAppThread);
5799 try {
5800 am.finishInstrumentation(mAppThread, resultCode, results);
5801 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005802 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 }
5804 }
5805
Romain Guy65b345f2011-07-27 18:51:50 -07005806 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 Context context, List<ProviderInfo> providers) {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005808 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809
Romain Guya998dff2012-03-23 18:58:36 -07005810 for (ProviderInfo cpi : providers) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08005811 if (DEBUG_PROVIDER) {
5812 StringBuilder buf = new StringBuilder(128);
5813 buf.append("Pub ");
5814 buf.append(cpi.authority);
5815 buf.append(": ");
5816 buf.append(cpi.name);
5817 Log.i(TAG, buf.toString());
5818 }
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005819 ContentProviderHolder cph = installProvider(context, null, cpi,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005820 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
5821 if (cph != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005822 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 }
5825 }
5826
5827 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005828 ActivityManager.getService().publishContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 getApplicationThread(), results);
5830 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005831 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 }
5833 }
5834
Jeff Sharkey6d515712012-09-20 16:06:08 -07005835 public final IContentProvider acquireProvider(
5836 Context c, String auth, int userId, boolean stable) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07005837 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005838 if (provider != null) {
5839 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 }
5841
Wale Ogunwale1d646122015-04-24 14:45:14 -07005842 // There is a possible race here. Another thread may try to acquire
5843 // the same provider at the same time. When this happens, we want to ensure
5844 // that the first one wins.
5845 // Note that we cannot hold the lock while acquiring and installing the
5846 // provider since it might take a long time to run and it could also potentially
5847 // be re-entrant in the case where the provider is in the same process.
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005848 ContentProviderHolder holder = null;
Wale Ogunwale1d646122015-04-24 14:45:14 -07005849 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005850 holder = ActivityManager.getService().getContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07005851 getApplicationThread(), auth, userId, stable);
5852 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005853 throw ex.rethrowFromSystemServer();
Wale Ogunwale67fe0a42015-04-24 14:44:54 -07005854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 if (holder == null) {
Jeff Sharkey6d515712012-09-20 16:06:08 -07005856 Slog.e(TAG, "Failed to find provider info for " + auth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 return null;
5858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005860 // Install provider will increment the reference count for us, and break
5861 // any ties in the race.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005862 holder = installProvider(c, holder, holder.info,
5863 true /*noisy*/, holder.noReleaseNeeded, stable);
5864 return holder.provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 }
5866
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005867 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
5868 if (stable) {
5869 prc.stableCount += 1;
5870 if (prc.stableCount == 1) {
5871 // We are acquiring a new stable reference on the provider.
5872 int unstableDelta;
5873 if (prc.removePending) {
5874 // We have a pending remove operation, which is holding the
5875 // last unstable reference. At this point we are converting
5876 // that unstable reference to our new stable reference.
5877 unstableDelta = -1;
5878 // Cancel the removal of the provider.
5879 if (DEBUG_PROVIDER) {
5880 Slog.v(TAG, "incProviderRef: stable "
5881 + "snatched provider from the jaws of death");
5882 }
5883 prc.removePending = false;
Guobin Zhang9e3e52662013-03-21 13:57:11 +08005884 // There is a race! It fails to remove the message, which
5885 // will be handled in completeRemoveProvider().
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005886 mH.removeMessages(H.REMOVE_PROVIDER, prc);
5887 } else {
5888 unstableDelta = 0;
5889 }
5890 try {
5891 if (DEBUG_PROVIDER) {
5892 Slog.v(TAG, "incProviderRef Now stable - "
5893 + prc.holder.info.name + ": unstableDelta="
5894 + unstableDelta);
5895 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005896 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005897 prc.holder.connection, 1, unstableDelta);
5898 } catch (RemoteException e) {
5899 //do nothing content provider object is dead any way
5900 }
5901 }
5902 } else {
5903 prc.unstableCount += 1;
5904 if (prc.unstableCount == 1) {
5905 // We are acquiring a new unstable reference on the provider.
5906 if (prc.removePending) {
5907 // Oh look, we actually have a remove pending for the
5908 // provider, which is still holding the last unstable
5909 // reference. We just need to cancel that to take new
5910 // ownership of the reference.
5911 if (DEBUG_PROVIDER) {
5912 Slog.v(TAG, "incProviderRef: unstable "
5913 + "snatched provider from the jaws of death");
5914 }
5915 prc.removePending = false;
5916 mH.removeMessages(H.REMOVE_PROVIDER, prc);
5917 } else {
5918 // First unstable ref, increment our count in the
5919 // activity manager.
5920 try {
5921 if (DEBUG_PROVIDER) {
5922 Slog.v(TAG, "incProviderRef: Now unstable - "
5923 + prc.holder.info.name);
5924 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005925 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005926 prc.holder.connection, 0, 1);
5927 } catch (RemoteException e) {
5928 //do nothing content provider object is dead any way
5929 }
5930 }
5931 }
5932 }
5933 }
5934
Jeff Sharkey6d515712012-09-20 16:06:08 -07005935 public final IContentProvider acquireExistingProvider(
5936 Context c, String auth, int userId, boolean stable) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005937 synchronized (mProviderMap) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07005938 final ProviderKey key = new ProviderKey(auth, userId);
Jeff Sharkey6d515712012-09-20 16:06:08 -07005939 final ProviderClientRecord pr = mProviderMap.get(key);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005940 if (pr == null) {
5941 return null;
5942 }
5943
5944 IContentProvider provider = pr.mProvider;
5945 IBinder jBinder = provider.asBinder();
Dianne Hackbornc428aae2012-10-03 16:38:22 -07005946 if (!jBinder.isBinderAlive()) {
5947 // The hosting process of the provider has died; we can't
5948 // use this one.
Wale Ogunwale1d646122015-04-24 14:45:14 -07005949 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
Dianne Hackbornc428aae2012-10-03 16:38:22 -07005950 + ": existing object's process dead");
5951 handleUnstableProviderDiedLocked(jBinder, true);
5952 return null;
5953 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005954
5955 // Only increment the ref count if we have one. If we don't then the
5956 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07005957 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005958 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005959 incProviderRefLocked(prc, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005960 }
5961 return provider;
5962 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07005963 }
5964
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005965 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
5966 if (provider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 return false;
5968 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005971 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005973 if (prc == null) {
5974 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005976 }
5977
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005978 boolean lastRef = false;
5979 if (stable) {
5980 if (prc.stableCount == 0) {
5981 if (DEBUG_PROVIDER) Slog.v(TAG,
5982 "releaseProvider: stable ref count already 0, how?");
5983 return false;
5984 }
5985 prc.stableCount -= 1;
5986 if (prc.stableCount == 0) {
5987 // What we do at this point depends on whether there are
5988 // any unstable refs left: if there are, we just tell the
5989 // activity manager to decrement its stable count; if there
5990 // aren't, we need to enqueue this provider to be removed,
5991 // and convert to holding a single unstable ref while
5992 // doing so.
5993 lastRef = prc.unstableCount == 0;
5994 try {
5995 if (DEBUG_PROVIDER) {
5996 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
5997 + lastRef + " - " + prc.holder.info.name);
5998 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005999 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006000 prc.holder.connection, -1, lastRef ? 1 : 0);
6001 } catch (RemoteException e) {
6002 //do nothing content provider object is dead any way
6003 }
6004 }
6005 } else {
6006 if (prc.unstableCount == 0) {
6007 if (DEBUG_PROVIDER) Slog.v(TAG,
6008 "releaseProvider: unstable ref count already 0, how?");
6009 return false;
6010 }
6011 prc.unstableCount -= 1;
6012 if (prc.unstableCount == 0) {
6013 // If this is the last reference, we need to enqueue
6014 // this provider to be removed instead of telling the
6015 // activity manager to remove it at this point.
6016 lastRef = prc.stableCount == 0;
6017 if (!lastRef) {
6018 try {
6019 if (DEBUG_PROVIDER) {
6020 Slog.v(TAG, "releaseProvider: No longer unstable - "
6021 + prc.holder.info.name);
6022 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006023 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006024 prc.holder.connection, 0, -1);
6025 } catch (RemoteException e) {
6026 //do nothing content provider object is dead any way
6027 }
6028 }
6029 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006030 }
6031
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006032 if (lastRef) {
6033 if (!prc.removePending) {
6034 // Schedule the actual remove asynchronously, since we don't know the context
6035 // this will be called in.
6036 // TODO: it would be nice to post a delayed message, so
6037 // if we come back and need the same provider quickly
6038 // we will still have it available.
6039 if (DEBUG_PROVIDER) {
6040 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
6041 + prc.holder.info.name);
6042 }
6043 prc.removePending = true;
6044 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
6045 mH.sendMessage(msg);
6046 } else {
6047 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
6048 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006049 }
6050 return true;
6051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 }
6053
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006054 final void completeRemoveProvider(ProviderRefCount prc) {
6055 synchronized (mProviderMap) {
6056 if (!prc.removePending) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006057 // There was a race! Some other client managed to acquire
6058 // the provider before the removal was completed.
6059 // Abort the removal. We will do it later.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006060 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006061 + "provider still in use");
6062 return;
6063 }
6064
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006065 // More complicated race!! Some client managed to acquire the
6066 // provider and release it before the removal was completed.
6067 // Continue the removal, and abort the next remove message.
6068 prc.removePending = false;
6069
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006070 final IBinder jBinder = prc.holder.provider.asBinder();
6071 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
6072 if (existingPrc == prc) {
6073 mProviderRefCountMap.remove(jBinder);
6074 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006075
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006076 for (int i=mProviderMap.size()-1; i>=0; i--) {
6077 ProviderClientRecord pr = mProviderMap.valueAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006078 IBinder myBinder = pr.mProvider.asBinder();
6079 if (myBinder == jBinder) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006080 mProviderMap.removeAt(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006081 }
6082 }
6083 }
6084
6085 try {
6086 if (DEBUG_PROVIDER) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006087 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006088 + "removeContentProvider(" + prc.holder.info.name + ")");
6089 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006090 ActivityManager.getService().removeContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006091 prc.holder.connection, false);
6092 } catch (RemoteException e) {
6093 //do nothing content provider object is dead any way
6094 }
6095 }
6096
6097 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006098 synchronized (mProviderMap) {
6099 handleUnstableProviderDiedLocked(provider, fromClient);
6100 }
6101 }
6102
6103 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
6104 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6105 if (prc != null) {
6106 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
6107 + provider + " " + prc.holder.info.name);
6108 mProviderRefCountMap.remove(provider);
You Kimbc74de62013-10-01 00:13:26 +09006109 for (int i=mProviderMap.size()-1; i>=0; i--) {
6110 ProviderClientRecord pr = mProviderMap.valueAt(i);
6111 if (pr != null && pr.mProvider.asBinder() == provider) {
6112 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
6113 mProviderMap.removeAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006114 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006115 }
You Kimbc74de62013-10-01 00:13:26 +09006116
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006117 if (fromClient) {
6118 // We found out about this due to execution in our client
6119 // code. Tell the activity manager about it now, to ensure
6120 // that the next time we go to do anything with the provider
6121 // it knows it is dead (so we don't race with its death
6122 // notification).
6123 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006124 ActivityManager.getService().unstableProviderDied(
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006125 prc.holder.connection);
6126 } catch (RemoteException e) {
6127 //do nothing content provider object is dead any way
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006128 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07006129 }
6130 }
6131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006133 final void appNotRespondingViaProvider(IBinder provider) {
6134 synchronized (mProviderMap) {
6135 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6136 if (prc != null) {
6137 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006138 ActivityManager.getService()
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006139 .appNotRespondingViaProvider(prc.holder.connection);
6140 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006141 throw e.rethrowFromSystemServer();
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006142 }
6143 }
6144 }
6145 }
6146
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006147 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006148 ContentProvider localProvider, ContentProviderHolder holder) {
Andreas Gampe18e99c12015-03-06 15:29:06 -08006149 final String auths[] = holder.info.authority.split(";");
Jeff Sharkey6d515712012-09-20 16:06:08 -07006150 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
6151
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006152 if (provider != null) {
6153 // If this provider is hosted by the core OS and cannot be upgraded,
6154 // then I guess we're okay doing blocking calls to it.
6155 for (String auth : auths) {
6156 switch (auth) {
6157 case ContactsContract.AUTHORITY:
6158 case CallLog.AUTHORITY:
6159 case CallLog.SHADOW_AUTHORITY:
6160 case BlockedNumberContract.AUTHORITY:
6161 case CalendarContract.AUTHORITY:
6162 case Downloads.Impl.AUTHORITY:
Jeff Sharkeycb621622016-11-11 14:04:32 -07006163 case "telephony":
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006164 Binder.allowBlocking(provider.asBinder());
6165 }
6166 }
6167 }
6168
Jeff Sharkey6d515712012-09-20 16:06:08 -07006169 final ProviderClientRecord pcr = new ProviderClientRecord(
6170 auths, provider, localProvider, holder);
6171 for (String auth : auths) {
6172 final ProviderKey key = new ProviderKey(auth, userId);
6173 final ProviderClientRecord existing = mProviderMap.get(key);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006174 if (existing != null) {
6175 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
Jeff Sharkey6d515712012-09-20 16:06:08 -07006176 + " already published as " + auth);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006177 } else {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006178 mProviderMap.put(key, pcr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 }
6180 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006181 return pcr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 }
6183
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006184 /**
6185 * Installs the provider.
6186 *
6187 * Providers that are local to the process or that come from the system server
6188 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
6189 * Other remote providers are reference counted. The initial reference count
6190 * for all reference counted providers is one. Providers that are not reference
6191 * counted do not have a reference count (at all).
6192 *
6193 * This method detects when a provider has already been installed. When this happens,
6194 * it increments the reference count of the existing provider (if appropriate)
6195 * and returns the existing provider. This can happen due to concurrent
6196 * attempts to acquire the same provider.
6197 */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006198 private ContentProviderHolder installProvider(Context context,
6199 ContentProviderHolder holder, ProviderInfo info,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006200 boolean noisy, boolean noReleaseNeeded, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 ContentProvider localProvider = null;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006202 IContentProvider provider;
Dianne Hackborn5f48fca2012-05-30 11:06:31 -07006203 if (holder == null || holder.provider == null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006204 if (DEBUG_PROVIDER || noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006205 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 + info.name);
6207 }
6208 Context c = null;
6209 ApplicationInfo ai = info.applicationInfo;
6210 if (context.getPackageName().equals(ai.packageName)) {
6211 c = context;
6212 } else if (mInitialApplication != null &&
6213 mInitialApplication.getPackageName().equals(ai.packageName)) {
6214 c = mInitialApplication;
6215 } else {
6216 try {
6217 c = context.createPackageContext(ai.packageName,
6218 Context.CONTEXT_INCLUDE_CODE);
6219 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07006220 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 }
6222 }
6223 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006224 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 ai.packageName +
6226 " while loading content provider " +
6227 info.name);
6228 return null;
6229 }
Adam Lesinski4e862812016-11-21 16:02:24 -08006230
6231 if (info.splitName != null) {
6232 try {
6233 c = c.createContextForSplit(info.splitName);
6234 } catch (NameNotFoundException e) {
6235 throw new RuntimeException(e);
6236 }
6237 }
6238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 try {
6240 final java.lang.ClassLoader cl = c.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04006241 localProvider = (ContentProvider)cl.
6242 loadClass(info.name).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 provider = localProvider.getIContentProvider();
6244 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006245 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 info.name + " from sourceDir " +
6247 info.applicationInfo.sourceDir);
6248 return null;
6249 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006250 if (DEBUG_PROVIDER) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 TAG, "Instantiating local provider " + info.name);
6252 // XXX Need to create the correct context for this provider.
6253 localProvider.attachInfo(c, info);
6254 } catch (java.lang.Exception e) {
6255 if (!mInstrumentation.onException(null, e)) {
6256 throw new RuntimeException(
6257 "Unable to get provider " + info.name
6258 + ": " + e.toString(), e);
6259 }
6260 return null;
6261 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006262 } else {
6263 provider = holder.provider;
6264 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 + info.name);
6266 }
6267
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006268 ContentProviderHolder retHolder;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006269
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006270 synchronized (mProviderMap) {
6271 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
6272 + " / " + info.name);
6273 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 if (localProvider != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006275 ComponentName cname = new ComponentName(info.packageName, info.name);
6276 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006277 if (pr != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006278 if (DEBUG_PROVIDER) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006279 Slog.v(TAG, "installProvider: lost the race, "
6280 + "using existing local provider");
6281 }
6282 provider = pr.mProvider;
6283 } else {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006284 holder = new ContentProviderHolder(info);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006285 holder.provider = provider;
6286 holder.noReleaseNeeded = true;
6287 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006288 mLocalProviders.put(jBinder, pr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006289 mLocalProvidersByName.put(cname, pr);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006290 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006291 retHolder = pr.mHolder;
6292 } else {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006293 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
6294 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006295 if (DEBUG_PROVIDER) {
6296 Slog.v(TAG, "installProvider: lost the race, updating ref count");
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006297 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006298 // We need to transfer our new reference to the existing
6299 // ref count, releasing the old one... but only if
6300 // release is needed (that is, it is not running in the
6301 // system process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006302 if (!noReleaseNeeded) {
6303 incProviderRefLocked(prc, stable);
Wale Ogunwale1d646122015-04-24 14:45:14 -07006304 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006305 ActivityManager.getService().removeContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07006306 holder.connection, stable);
6307 } catch (RemoteException e) {
6308 //do nothing content provider object is dead any way
6309 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006310 }
6311 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006312 ProviderClientRecord client = installProviderAuthoritiesLocked(
6313 provider, localProvider, holder);
6314 if (noReleaseNeeded) {
6315 prc = new ProviderRefCount(holder, client, 1000, 1000);
6316 } else {
6317 prc = stable
6318 ? new ProviderRefCount(holder, client, 1, 0)
6319 : new ProviderRefCount(holder, client, 0, 1);
6320 }
6321 mProviderRefCountMap.put(jBinder, prc);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006322 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006323 retHolder = prc.holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 }
6325 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006326 return retHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 }
6328
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04006329 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
6330 try {
6331 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
6332 main.invoke(null, new Object[]{entryPointArgs});
6333 } catch (ReflectiveOperationException e) {
6334 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
6335 }
6336 // The process will be empty after this method returns; exit the VM now.
6337 System.exit(0);
6338 }
6339
Romain Guy65b345f2011-07-27 18:51:50 -07006340 private void attach(boolean system) {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08006341 sCurrentActivityThread = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006344 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Craig Mautner88c05892013-06-28 09:47:45 -07006345 @Override
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08006346 public void run() {
6347 ensureJitEnabled();
6348 }
6349 });
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006350 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
6351 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 RuntimeInit.setApplicationObject(mAppThread.asBinder());
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006353 final IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 try {
6355 mgr.attachApplication(mAppThread);
6356 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006357 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006359 // Watch for getting close to heap limit.
6360 BinderInternal.addGcWatcher(new Runnable() {
6361 @Override public void run() {
6362 if (!mSomeActivitiesChanged) {
6363 return;
6364 }
6365 Runtime runtime = Runtime.getRuntime();
6366 long dalvikMax = runtime.maxMemory();
6367 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
6368 if (dalvikUsed > ((3*dalvikMax)/4)) {
6369 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
6370 + " total=" + (runtime.totalMemory()/1024)
6371 + " used=" + (dalvikUsed/1024));
6372 mSomeActivitiesChanged = false;
6373 try {
6374 mgr.releaseSomeActivities(mAppThread);
6375 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006376 throw e.rethrowFromSystemServer();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006377 }
6378 }
6379 }
6380 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 } else {
6382 // Don't set application object here -- if the system crashes,
6383 // we can't display an alert, we just want to die die die.
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006384 android.ddm.DdmHandleAppName.setAppName("system_process",
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006385 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 try {
6387 mInstrumentation = new Instrumentation();
Jeff Browndefd4a62014-03-10 21:24:37 -07006388 ContextImpl context = ContextImpl.createAppContext(
6389 this, getSystemContext().mPackageInfo);
Jeff Brown7fc8e352014-09-16 18:06:47 -07006390 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
6391 mInitialApplication.onCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 } catch (Exception e) {
6393 throw new RuntimeException(
6394 "Unable to instantiate Application():" + e.toString(), e);
6395 }
6396 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006397
6398 // add dropbox logging to libcore
6399 DropBox.setReporter(new DropBoxReporter());
6400
Andrii Kulian44607962017-03-16 11:06:24 -07006401 ViewRootImpl.ConfigChangedCallback configChangedCallback
6402 = (Configuration globalConfig) -> {
6403 synchronized (mResourcesManager) {
6404 // We need to apply this change to the resources immediately, because upon returning
6405 // the view hierarchy will be informed about it.
6406 if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
6407 null /* compat */)) {
6408 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
6409 mResourcesManager.getConfiguration().getLocales());
Adam Lesinskib61e4052016-05-19 18:23:05 -07006410
Andrii Kulian44607962017-03-16 11:06:24 -07006411 // This actually changed the resources! Tell everyone about it.
6412 if (mPendingConfiguration == null
6413 || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
6414 mPendingConfiguration = globalConfig;
6415 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006416 }
6417 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006418 }
Andrii Kulian44607962017-03-16 11:06:24 -07006419 };
6420 ViewRootImpl.addConfigCallback(configChangedCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 }
6422
Romain Guy5e9120d2012-01-30 12:17:22 -08006423 public static ActivityThread systemMain() {
Alan Viverette5e1565e2014-07-29 16:14:25 -07006424 // The system process on low-memory devices do not get to use hardware
6425 // accelerated drawing, since this can add too much overhead to the
6426 // process.
6427 if (!ActivityManager.isHighEndGfx()) {
John Reck51aaf902015-12-02 15:08:07 -08006428 ThreadedRenderer.disable(true);
John Reck73840ea2014-09-22 07:39:18 -07006429 } else {
John Reck51aaf902015-12-02 15:08:07 -08006430 ThreadedRenderer.enableForegroundTrimming();
Alan Viverette5e1565e2014-07-29 16:14:25 -07006431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006432 ActivityThread thread = new ActivityThread();
6433 thread.attach(true);
6434 return thread;
6435 }
6436
Jeff Brown10e89712011-07-08 18:52:57 -07006437 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07006439 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 }
6441 }
6442
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006443 public int getIntCoreSetting(String key, int defaultValue) {
Craig Mautner88c05892013-06-28 09:47:45 -07006444 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08006445 if (mCoreSettings != null) {
6446 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006447 }
Craig Mautner88c05892013-06-28 09:47:45 -07006448 return defaultValue;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006449 }
6450 }
6451
Geremy Condra69689a72012-09-11 16:57:17 -07006452 private static class EventLoggingReporter implements EventLogger.Reporter {
6453 @Override
6454 public void report (int code, Object... list) {
6455 EventLog.writeEvent(code, list);
6456 }
6457 }
6458
Geremy Condrab7faaf42012-09-19 18:07:42 -07006459 private class DropBoxReporter implements DropBox.Reporter {
6460
6461 private DropBoxManager dropBox;
6462
Narayan Kamath7f062242015-04-08 13:24:13 +01006463 public DropBoxReporter() {}
Geremy Condrab7faaf42012-09-19 18:07:42 -07006464
6465 @Override
6466 public void addData(String tag, byte[] data, int flags) {
Narayan Kamath7f062242015-04-08 13:24:13 +01006467 ensureInitialized();
Geremy Condrab7faaf42012-09-19 18:07:42 -07006468 dropBox.addData(tag, data, flags);
6469 }
6470
6471 @Override
6472 public void addText(String tag, String data) {
Narayan Kamath7f062242015-04-08 13:24:13 +01006473 ensureInitialized();
Geremy Condrab7faaf42012-09-19 18:07:42 -07006474 dropBox.addText(tag, data);
6475 }
Narayan Kamath7f062242015-04-08 13:24:13 +01006476
6477 private synchronized void ensureInitialized() {
6478 if (dropBox == null) {
6479 dropBox = (DropBoxManager) getSystemContext().getSystemService(Context.DROPBOX_SERVICE);
6480 }
6481 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006482 }
6483
Romain Guy65b345f2011-07-27 18:51:50 -07006484 public static void main(String[] args) {
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006485 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
Bob Leee5408332009-09-04 18:31:17 -07006486
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08006487 // CloseGuard defaults to true and can be quite spammy. We
6488 // disable it here, but selectively enable it later (via
6489 // StrictMode) on debug builds, but using DropBox, not logs.
6490 CloseGuard.setEnabled(false);
6491
Andreas Gamped281b422016-07-08 03:50:27 +00006492 Environment.initForCurrentUser();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006493
Geremy Condra69689a72012-09-11 16:57:17 -07006494 // Set the reporter for event logging in libcore
6495 EventLogger.setReporter(new EventLoggingReporter());
6496
Robin Lee3d076af2014-04-25 14:57:49 +01006497 // Make sure TrustedCertificateStore looks in the right place for CA certificates
6498 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
6499 TrustedCertificateStore.setDefaultUserDirectory(configDir);
6500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 Process.setArgV0("<pre-initialized>");
6502
6503 Looper.prepareMainLooper();
6504
6505 ActivityThread thread = new ActivityThread();
6506 thread.attach(false);
6507
Vairavan Srinivasan7335cfd2012-08-18 18:36:03 -07006508 if (sMainThreadHandler == null) {
6509 sMainThreadHandler = thread.getHandler();
6510 }
6511
Dianne Hackborn287952c2010-09-22 22:34:31 -07006512 if (false) {
6513 Looper.myLooper().setMessageLogging(new
6514 LogPrinter(Log.DEBUG, "ActivityThread"));
6515 }
6516
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006517 // End of event ActivityThreadMain.
6518 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 Looper.loop();
6520
Jeff Brown10e89712011-07-08 18:52:57 -07006521 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 }
Chris Craikfc294242016-12-13 18:10:46 -08006523
6524 // ------------------ Regular JNI ------------------------
6525
6526 private native void nDumpGraphicsInfo(FileDescriptor fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527}