blob: f2e7c9876199748c26ad4b00fc9a0c9710ec121a [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
Christopher Tate45281862010-03-05 15:46:30 -080019import android.app.backup.BackupAgent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070021import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.ComponentName;
23import android.content.ContentProvider;
24import android.content.Context;
25import android.content.IContentProvider;
26import android.content.Intent;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070027import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.ActivityInfo;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.IPackageManager;
31import android.content.pm.InstrumentationInfo;
32import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070033import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.pm.ProviderInfo;
35import android.content.pm.ServiceInfo;
36import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070037import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080042import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.Bitmap;
44import android.graphics.Canvas;
Robert Greenwalt434203a2010-10-11 16:00:27 -070045import android.net.IConnectivityManager;
46import android.net.Proxy;
47import android.net.ProxyProperties;
Romain Guya9582652011-11-10 14:20:10 -080048import android.opengl.GLUtils;
Joe Onoratod630f102011-03-17 18:42:26 -070049import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070050import android.os.Binder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.Bundle;
52import android.os.Debug;
53import android.os.Handler;
54import android.os.IBinder;
55import android.os.Looper;
56import android.os.Message;
57import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070058import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.Process;
60import android.os.RemoteException;
61import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070062import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.SystemClock;
Amith Yamasani742a6712011-05-04 14:49:28 -070064import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.util.AndroidRuntimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.util.DisplayMetrics;
67import android.util.EventLog;
68import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -070069import android.util.LogPrinter;
Jeff Brown6754ba22011-12-14 20:20:01 -080070import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080071import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.view.Display;
Romain Guy52339202010-09-03 16:04:46 -070073import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.view.View;
75import android.view.ViewDebug;
76import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -070077import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.view.Window;
79import android.view.WindowManager;
80import android.view.WindowManagerImpl;
Jason Samsa6f338c2012-02-24 16:22:16 -080081import android.renderscript.RenderScript;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
83import com.android.internal.os.BinderInternal;
84import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070085import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
87import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
88
89import java.io.File;
90import java.io.FileDescriptor;
91import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070092import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import java.io.PrintWriter;
94import java.lang.ref.WeakReference;
Robert Greenwalt03595d02010-11-02 14:08:23 -070095import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import java.util.ArrayList;
97import java.util.HashMap;
98import java.util.Iterator;
99import java.util.List;
100import java.util.Locale;
101import java.util.Map;
102import java.util.TimeZone;
103import java.util.regex.Pattern;
104
Jeff Sharkeye861b422012-03-01 20:59:22 -0800105import libcore.io.IoUtils;
106
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -0800107import dalvik.system.CloseGuard;
Bob Leee5408332009-09-04 18:31:17 -0700108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109final class SuperNotCalledException extends AndroidRuntimeException {
110 public SuperNotCalledException(String msg) {
111 super(msg);
112 }
113}
114
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700115final class RemoteServiceException extends AndroidRuntimeException {
116 public RemoteServiceException(String msg) {
117 super(msg);
118 }
119}
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121/**
122 * This manages the execution of the main thread in an
123 * application process, scheduling and executing activities,
124 * broadcasts, and other operations on it as the activity
125 * manager requests.
126 *
127 * {@hide}
128 */
129public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700130 /** @hide */
131 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700132 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700133 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700134 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700135 /** @hide */
136 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700137 private static final boolean DEBUG_RESULTS = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700138 private static final boolean DEBUG_BACKUP = true;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700139 private static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800140 private static final boolean DEBUG_SERVICE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
142 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
143 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
144 private static final int LOG_ON_PAUSE_CALLED = 30021;
145 private static final int LOG_ON_RESUME_CALLED = 30022;
146
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700147 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700149 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700151 final ApplicationThread mAppThread = new ApplicationThread();
152 final Looper mLooper = Looper.myLooper();
153 final H mH = new H();
154 final HashMap<IBinder, ActivityClientRecord> mActivities
155 = new HashMap<IBinder, ActivityClientRecord>();
156 // List of new activities (via ActivityRecord.nextIdle) that should
157 // be reported when next we idle.
158 ActivityClientRecord mNewActivities = null;
159 // Number of activities that are currently visible on-screen.
160 int mNumVisibleActivities = 0;
161 final HashMap<IBinder, Service> mServices
162 = new HashMap<IBinder, Service>();
163 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700164 Profiler mProfiler;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700165 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700166 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700167 Configuration mResConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700168 CompatibilityInfo mResCompatibilityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700169 Application mInitialApplication;
170 final ArrayList<Application> mAllApplications
171 = new ArrayList<Application>();
172 // set of instantiated backup agents, keyed by package name
173 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Romain Guy65b345f2011-07-27 18:51:50 -0700174 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal<ActivityThread>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700175 Instrumentation mInstrumentation;
176 String mInstrumentationAppDir = null;
177 String mInstrumentationAppPackage = null;
178 String mInstrumentedAppDir = null;
179 boolean mSystemThread = false;
180 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700182 // These can be accessed by multiple threads; mPackages is the lock.
183 // XXX For now we keep around information about all packages we have
184 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800185 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700186 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800187 // which means this lock gets held while the activity and window managers
188 // holds their own lock. Thus you MUST NEVER call back into the activity manager
189 // or window manager or anything that depends on them while holding this lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700190 final HashMap<String, WeakReference<LoadedApk>> mPackages
191 = new HashMap<String, WeakReference<LoadedApk>>();
192 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
193 = new HashMap<String, WeakReference<LoadedApk>>();
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700194 final HashMap<CompatibilityInfo, DisplayMetrics> mDisplayMetrics
195 = new HashMap<CompatibilityInfo, DisplayMetrics>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700196 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
197 = new HashMap<ResourcesKey, WeakReference<Resources> >();
198 final ArrayList<ActivityClientRecord> mRelaunchingActivities
199 = new ArrayList<ActivityClientRecord>();
200 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700202 // The lock of mProviderMap protects the following variables.
203 final HashMap<String, ProviderClientRecord> mProviderMap
204 = new HashMap<String, ProviderClientRecord>();
205 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
206 = new HashMap<IBinder, ProviderRefCount>();
207 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
208 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Jeff Hamilton52d32032011-01-08 15:31:26 -0600210 final HashMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
211 = new HashMap<Activity, ArrayList<OnActivityPausedListener>>();
212
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700213 final GcIdler mGcIdler = new GcIdler();
214 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700216 static Handler sMainThreadHandler; // set once in main()
217
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800218 Bundle mCoreSettings = null;
219
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400220 static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700222 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 Intent intent;
224 Bundle state;
225 Activity activity;
226 Window window;
227 Activity parent;
228 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700229 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 boolean paused;
231 boolean stopped;
232 boolean hideForNow;
233 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700234 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700235 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700237 String profileFile;
238 ParcelFileDescriptor profileFd;
239 boolean autoStopProfiler;
240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400242 CompatibilityInfo compatInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700243 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
245 List<ResultInfo> pendingResults;
246 List<Intent> pendingIntents;
247
248 boolean startsNotResumed;
249 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800250 int pendingConfigChanges;
251 boolean onlyLocalRequest;
252
253 View mPendingRemoveWindow;
254 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700256 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 parent = null;
258 embeddedID = null;
259 paused = false;
260 stopped = false;
261 hideForNow = false;
262 nextIdle = null;
263 }
264
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800265 public boolean isPreHoneycomb() {
266 if (activity != null) {
267 return activity.getApplicationInfo().targetSdkVersion
268 < android.os.Build.VERSION_CODES.HONEYCOMB;
269 }
270 return false;
271 }
272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 public String toString() {
274 ComponentName componentName = intent.getComponent();
275 return "ActivityRecord{"
276 + Integer.toHexString(System.identityHashCode(this))
277 + " token=" + token + " " + (componentName == null
278 ? "no component name" : componentName.toShortString())
279 + "}";
280 }
281 }
282
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400283 final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 final String mName;
285 final IContentProvider mProvider;
286 final ContentProvider mLocalProvider;
287
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700288 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 ContentProvider localProvider) {
290 mName = name;
291 mProvider = provider;
292 mLocalProvider = localProvider;
293 }
294
295 public void binderDied() {
296 removeDeadProvider(mName, mProvider);
297 }
298 }
299
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400300 static final class NewIntentData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 List<Intent> intents;
302 IBinder token;
303 public String toString() {
304 return "NewIntentData{intents=" + intents + " token=" + token + "}";
305 }
306 }
307
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400308 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700309 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
310 boolean ordered, boolean sticky, IBinder token) {
311 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
312 this.intent = intent;
313 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 Intent intent;
316 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400317 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 public String toString() {
319 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700320 info.packageName + " resultCode=" + getResultCode()
321 + " resultData=" + getResultData() + " resultExtras="
322 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 }
324 }
325
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400326 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700327 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400328 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700329 int backupMode;
330 public String toString() {
331 return "CreateBackupAgentData{appInfo=" + appInfo
332 + " backupAgent=" + appInfo.backupAgentName
333 + " mode=" + backupMode + "}";
334 }
335 }
Bob Leee5408332009-09-04 18:31:17 -0700336
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400337 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 IBinder token;
339 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400340 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 Intent intent;
342 public String toString() {
343 return "CreateServiceData{token=" + token + " className="
344 + info.name + " packageName=" + info.packageName
345 + " intent=" + intent + "}";
346 }
347 }
348
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400349 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 IBinder token;
351 Intent intent;
352 boolean rebind;
353 public String toString() {
354 return "BindServiceData{token=" + token + " intent=" + intent + "}";
355 }
356 }
357
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400358 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700360 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700362 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 Intent args;
364 public String toString() {
365 return "ServiceArgsData{token=" + token + " startId=" + startId
366 + " args=" + args + "}";
367 }
368 }
369
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400370 static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700371 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 String processName;
373 ApplicationInfo appInfo;
374 List<ProviderInfo> providers;
375 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 Bundle instrumentationArgs;
377 IInstrumentationWatcher instrumentationWatcher;
378 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700379 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700380 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400382 CompatibilityInfo compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700383
384 /** Initial values for {@link Profiler}. */
385 String initProfileFile;
386 ParcelFileDescriptor initProfileFd;
387 boolean initAutoStopProfiler;
388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 public String toString() {
390 return "AppBindData{appInfo=" + appInfo + "}";
391 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700392 }
393
394 static final class Profiler {
395 String profileFile;
396 ParcelFileDescriptor profileFd;
397 boolean autoStopProfiler;
398 boolean profiling;
399 boolean handlingProfiling;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700400 public void setProfiler(String file, ParcelFileDescriptor fd) {
401 if (profiling) {
402 if (fd != null) {
403 try {
404 fd.close();
405 } catch (IOException e) {
406 }
407 }
408 return;
409 }
410 if (profileFd != null) {
411 try {
412 profileFd.close();
413 } catch (IOException e) {
414 }
415 }
416 profileFile = file;
417 profileFd = fd;
418 }
419 public void startProfiling() {
420 if (profileFd == null || profiling) {
421 return;
422 }
423 try {
424 Debug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
425 8 * 1024 * 1024, 0);
426 profiling = true;
427 } catch (RuntimeException e) {
428 Slog.w(TAG, "Profiling failed on path " + profileFile);
429 try {
430 profileFd.close();
431 profileFd = null;
432 } catch (IOException e2) {
433 Slog.w(TAG, "Failure closing profile fd", e2);
434 }
435 }
436 }
437 public void stopProfiling() {
438 if (profiling) {
439 profiling = false;
440 Debug.stopMethodTracing();
441 if (profileFd != null) {
442 try {
443 profileFd.close();
444 } catch (IOException e) {
445 }
446 }
447 profileFd = null;
448 profileFile = null;
449 }
450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400453 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700454 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700455 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800456 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 }
459
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400460 static final class ResultData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 IBinder token;
462 List<ResultInfo> results;
463 public String toString() {
464 return "ResultData{token=" + token + " results" + results + "}";
465 }
466 }
467
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400468 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800469 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 String what;
471 String who;
472 }
473
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400474 static final class ProfilerControlData {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700475 String path;
476 ParcelFileDescriptor fd;
477 }
478
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400479 static final class DumpHeapData {
Andy McFadden824c5102010-07-09 16:26:57 -0700480 String path;
481 ParcelFileDescriptor fd;
482 }
483
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400484 static final class UpdateCompatibilityData {
485 String pkg;
486 CompatibilityInfo info;
487 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -0700488
Romain Guy65b345f2011-07-27 18:51:50 -0700489 private native void dumpGraphicsInfo(FileDescriptor fd);
Chet Haase9c1e23b2011-03-24 10:51:31 -0700490
Romain Guy65b345f2011-07-27 18:51:50 -0700491 private class ApplicationThread extends ApplicationThreadNative {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700492 private static final String HEAP_COLUMN = "%13s %8s %8s %8s %8s %8s %8s";
493 private static final String ONE_COUNT_COLUMN = "%21s %8d";
494 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700495 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 // Formatting for checkin service - update version if row format changes
498 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700499
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700500 private void updatePendingConfiguration(Configuration config) {
501 synchronized (mPackages) {
502 if (mPendingConfiguration == null ||
503 mPendingConfiguration.isOtherSeqNewer(config)) {
504 mPendingConfiguration = config;
505 }
506 }
507 }
508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 public final void schedulePauseActivity(IBinder token, boolean finished,
510 boolean userLeaving, int configChanges) {
511 queueOrSendMessage(
512 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
513 token,
514 (userLeaving ? 1 : 0),
515 configChanges);
516 }
517
518 public final void scheduleStopActivity(IBinder token, boolean showWindow,
519 int configChanges) {
520 queueOrSendMessage(
521 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
522 token, 0, configChanges);
523 }
524
525 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
526 queueOrSendMessage(
527 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
528 token);
529 }
530
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800531 public final void scheduleSleeping(IBinder token, boolean sleeping) {
532 queueOrSendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
533 }
534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
536 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
537 }
538
539 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
540 ResultData res = new ResultData();
541 res.token = token;
542 res.results = results;
543 queueOrSendMessage(H.SEND_RESULT, res);
544 }
545
546 // we use token to identify this activity without having to send the
547 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700548 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700549 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
550 Bundle state, List<ResultInfo> pendingResults,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700551 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
552 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700553 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554
555 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700556 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 r.intent = intent;
558 r.activityInfo = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400559 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 r.state = state;
561
562 r.pendingResults = pendingResults;
563 r.pendingIntents = pendingNewIntents;
564
565 r.startsNotResumed = notResumed;
566 r.isForward = isForward;
567
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700568 r.profileFile = profileName;
569 r.profileFd = profileFd;
570 r.autoStopProfiler = autoStopProfiler;
571
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700572 updatePendingConfiguration(curConfig);
573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
575 }
576
577 public final void scheduleRelaunchActivity(IBinder token,
578 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800579 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800580 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
581 configChanges, notResumed, config, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 }
583
584 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
585 NewIntentData data = new NewIntentData();
586 data.intents = intents;
587 data.token = token;
588
589 queueOrSendMessage(H.NEW_INTENT, data);
590 }
591
592 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
593 int configChanges) {
594 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
595 configChanges);
596 }
597
598 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400599 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
600 boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700601 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
602 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400604 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 queueOrSendMessage(H.RECEIVER, r);
606 }
607
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400608 public final void scheduleCreateBackupAgent(ApplicationInfo app,
609 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700610 CreateBackupAgentData d = new CreateBackupAgentData();
611 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400612 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700613 d.backupMode = backupMode;
614
615 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
616 }
617
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400618 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
619 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700620 CreateBackupAgentData d = new CreateBackupAgentData();
621 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400622 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700623
624 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
625 }
626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 public final void scheduleCreateService(IBinder token,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400628 ServiceInfo info, CompatibilityInfo compatInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 CreateServiceData s = new CreateServiceData();
630 s.token = token;
631 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400632 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633
634 queueOrSendMessage(H.CREATE_SERVICE, s);
635 }
636
637 public final void scheduleBindService(IBinder token, Intent intent,
638 boolean rebind) {
639 BindServiceData s = new BindServiceData();
640 s.token = token;
641 s.intent = intent;
642 s.rebind = rebind;
643
Amith Yamasani742a6712011-05-04 14:49:28 -0700644 if (DEBUG_SERVICE)
645 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
646 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 queueOrSendMessage(H.BIND_SERVICE, s);
648 }
649
650 public final void scheduleUnbindService(IBinder token, Intent intent) {
651 BindServiceData s = new BindServiceData();
652 s.token = token;
653 s.intent = intent;
654
655 queueOrSendMessage(H.UNBIND_SERVICE, s);
656 }
657
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700658 public final void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700659 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 ServiceArgsData s = new ServiceArgsData();
661 s.token = token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700662 s.taskRemoved = taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700664 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 s.args = args;
666
667 queueOrSendMessage(H.SERVICE_ARGS, s);
668 }
669
670 public final void scheduleStopService(IBinder token) {
671 queueOrSendMessage(H.STOP_SERVICE, token);
672 }
673
674 public final void bindApplication(String processName,
675 ApplicationInfo appInfo, List<ProviderInfo> providers,
676 ComponentName instrumentationName, String profileFile,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700677 ParcelFileDescriptor profileFd, boolean autoStopProfiler,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700679 int debugMode, boolean isRestrictedBackupMode, boolean persistent,
680 Configuration config, CompatibilityInfo compatInfo,
681 Map<String, IBinder> services, Bundle coreSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682
683 if (services != null) {
684 // Setup the service cache in the ServiceManager
685 ServiceManager.initServiceCache(services);
686 }
687
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800688 setCoreSettings(coreSettings);
689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 AppBindData data = new AppBindData();
691 data.processName = processName;
692 data.appInfo = appInfo;
693 data.providers = providers;
694 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 data.instrumentationArgs = instrumentationArgs;
696 data.instrumentationWatcher = instrumentationWatcher;
697 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700698 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700699 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400701 data.compatInfo = compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700702 data.initProfileFile = profileFile;
703 data.initProfileFd = profileFd;
704 data.initAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 queueOrSendMessage(H.BIND_APPLICATION, data);
706 }
707
708 public final void scheduleExit() {
709 queueOrSendMessage(H.EXIT_APPLICATION, null);
710 }
711
Christopher Tate5e1ab332009-09-01 20:32:49 -0700712 public final void scheduleSuicide() {
713 queueOrSendMessage(H.SUICIDE, null);
714 }
715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 public void requestThumbnail(IBinder token) {
717 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
718 }
719
720 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700721 updatePendingConfiguration(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
723 }
724
725 public void updateTimeZone() {
726 TimeZone.setDefault(null);
727 }
728
Robert Greenwalt03595d02010-11-02 14:08:23 -0700729 public void clearDnsCache() {
730 // a non-standard API to get this to libcore
731 InetAddress.clearDnsCache();
732 }
733
Robert Greenwalt434203a2010-10-11 16:00:27 -0700734 public void setHttpProxy(String host, String port, String exclList) {
735 Proxy.setHttpProxySystemProperty(host, port, exclList);
736 }
737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 public void processInBackground() {
739 mH.removeMessages(H.GC_WHEN_IDLE);
740 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
741 }
742
743 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700744 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700745 try {
746 data.fd = ParcelFileDescriptor.dup(fd);
747 data.token = servicetoken;
748 data.args = args;
749 queueOrSendMessage(H.DUMP_SERVICE, data);
750 } catch (IOException e) {
751 Slog.w(TAG, "dumpService failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 }
753 }
754
755 // This function exists to make sure all receiver dispatching is
756 // correctly ordered, since these are one-way calls and the binder driver
757 // applies transaction ordering per object for such calls.
758 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700759 int resultCode, String dataStr, Bundle extras, boolean ordered,
760 boolean sticky) throws RemoteException {
761 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
Bob Leee5408332009-09-04 18:31:17 -0700763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 public void scheduleLowMemory() {
765 queueOrSendMessage(H.LOW_MEMORY, null);
766 }
767
768 public void scheduleActivityConfigurationChanged(IBinder token) {
769 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
770 }
771
Romain Guy7eabe552011-07-21 14:56:34 -0700772 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd,
773 int profileType) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700774 ProfilerControlData pcd = new ProfilerControlData();
775 pcd.path = path;
776 pcd.fd = fd;
Romain Guy7eabe552011-07-21 14:56:34 -0700777 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800778 }
779
Andy McFadden824c5102010-07-09 16:26:57 -0700780 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
781 DumpHeapData dhd = new DumpHeapData();
782 dhd.path = path;
783 dhd.fd = fd;
784 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
785 }
786
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700787 public void setSchedulingGroup(int group) {
788 // Note: do this immediately, since going into the foreground
789 // should happen regardless of what pending work we have to do
790 // and the activity manager will wait for us to report back that
791 // we are done before sending us to the background.
792 try {
793 Process.setProcessGroup(Process.myPid(), group);
794 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800795 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700796 }
797 }
Bob Leee5408332009-09-04 18:31:17 -0700798
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700799 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
800 Debug.getMemoryInfo(outInfo);
801 }
Bob Leee5408332009-09-04 18:31:17 -0700802
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700803 public void dispatchPackageBroadcast(int cmd, String[] packages) {
804 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
805 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700806
807 public void scheduleCrash(String msg) {
808 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
809 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700810
Dianne Hackborn30d71892010-12-11 10:37:55 -0800811 public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
812 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700813 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700814 try {
815 data.fd = ParcelFileDescriptor.dup(fd);
816 data.token = activitytoken;
817 data.prefix = prefix;
818 data.args = args;
819 queueOrSendMessage(H.DUMP_ACTIVITY, data);
820 } catch (IOException e) {
821 Slog.w(TAG, "dumpActivity failed", e);
Dianne Hackborn625ac272010-09-17 18:29:22 -0700822 }
823 }
Chet Haase9c1e23b2011-03-24 10:51:31 -0700824
Marco Nelissen18cb2872011-11-15 11:19:53 -0800825 public void dumpProvider(FileDescriptor fd, IBinder providertoken,
826 String[] args) {
827 DumpComponentInfo data = new DumpComponentInfo();
828 try {
829 data.fd = ParcelFileDescriptor.dup(fd);
830 data.token = providertoken;
831 data.args = args;
832 queueOrSendMessage(H.DUMP_PROVIDER, data);
833 } catch (IOException e) {
834 Slog.w(TAG, "dumpProvider failed", e);
835 }
836 }
837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 @Override
Dianne Hackbornb437e092011-08-05 17:50:29 -0700839 public Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, boolean checkin,
840 boolean all, String[] args) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700841 FileOutputStream fout = new FileOutputStream(fd);
842 PrintWriter pw = new PrintWriter(fout);
843 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -0700844 return dumpMemInfo(pw, checkin, all, args);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700845 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -0700846 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -0700847 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700848 }
849
Dianne Hackbornb437e092011-08-05 17:50:29 -0700850 private Debug.MemoryInfo dumpMemInfo(PrintWriter pw, boolean checkin, boolean all,
851 String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 long nativeMax = Debug.getNativeHeapSize() / 1024;
853 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
854 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
855
856 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
857 Debug.getMemoryInfo(memInfo);
858
Dianne Hackbornb437e092011-08-05 17:50:29 -0700859 if (!all) {
860 return memInfo;
861 }
862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 Runtime runtime = Runtime.getRuntime();
864
865 long dalvikMax = runtime.totalMemory() / 1024;
866 long dalvikFree = runtime.freeMemory() / 1024;
867 long dalvikAllocated = dalvikMax - dalvikFree;
868 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -0700869 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700870 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
871 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 int globalAssetCount = AssetManager.getGlobalAssetCount();
873 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
874 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
875 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
876 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700877 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
Vasu Noric3849202010-03-09 10:47:25 -0800878 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 // For checkin, we print one long comma-separated list of values
Dianne Hackbornb437e092011-08-05 17:50:29 -0700881 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 // NOTE: if you change anything significant below, also consider changing
883 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700884 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 // Header
888 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
889 pw.print(Process.myPid()); pw.print(',');
890 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 // Heap info - max
893 pw.print(nativeMax); pw.print(',');
894 pw.print(dalvikMax); pw.print(',');
895 pw.print("N/A,");
896 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 // Heap info - allocated
899 pw.print(nativeAllocated); pw.print(',');
900 pw.print(dalvikAllocated); pw.print(',');
901 pw.print("N/A,");
902 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 // Heap info - free
905 pw.print(nativeFree); pw.print(',');
906 pw.print(dalvikFree); pw.print(',');
907 pw.print("N/A,");
908 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 // Heap info - proportional set size
911 pw.print(memInfo.nativePss); pw.print(',');
912 pw.print(memInfo.dalvikPss); pw.print(',');
913 pw.print(memInfo.otherPss); pw.print(',');
914 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 // Heap info - shared
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700917 pw.print(memInfo.nativeSharedDirty); pw.print(',');
918 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
919 pw.print(memInfo.otherSharedDirty); pw.print(',');
920 pw.print(memInfo.nativeSharedDirty + memInfo.dalvikSharedDirty
921 + memInfo.otherSharedDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 // Heap info - private
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700924 pw.print(memInfo.nativePrivateDirty); pw.print(',');
925 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
926 pw.print(memInfo.otherPrivateDirty); pw.print(',');
927 pw.print(memInfo.nativePrivateDirty + memInfo.dalvikPrivateDirty
928 + memInfo.otherPrivateDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 // Object counts
931 pw.print(viewInstanceCount); pw.print(',');
932 pw.print(viewRootInstanceCount); pw.print(',');
933 pw.print(appContextInstanceCount); pw.print(',');
934 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 pw.print(globalAssetCount); pw.print(',');
937 pw.print(globalAssetManagerCount); pw.print(',');
938 pw.print(binderLocalObjectCount); pw.print(',');
939 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 pw.print(binderDeathObjectCount); pw.print(',');
942 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 // SQL
Vasu Noric3849202010-03-09 10:47:25 -0800945 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -0800946 pw.print(stats.memoryUsed / 1024); pw.print(',');
947 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -0700948 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800949 for (int i = 0; i < stats.dbStats.size(); i++) {
950 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -0700951 pw.print(','); pw.print(dbStats.dbName);
952 pw.print(','); pw.print(dbStats.pageSize);
953 pw.print(','); pw.print(dbStats.dbSize);
954 pw.print(','); pw.print(dbStats.lookaside);
955 pw.print(','); pw.print(dbStats.cache);
956 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -0800957 }
Dianne Hackbornb437e092011-08-05 17:50:29 -0700958 pw.println();
Bob Leee5408332009-09-04 18:31:17 -0700959
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700960 return memInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
Bob Leee5408332009-09-04 18:31:17 -0700962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 // otherwise, show human-readable format
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700964 printRow(pw, HEAP_COLUMN, "", "", "Shared", "Private", "Heap", "Heap", "Heap");
965 printRow(pw, HEAP_COLUMN, "", "Pss", "Dirty", "Dirty", "Size", "Alloc", "Free");
966 printRow(pw, HEAP_COLUMN, "", "------", "------", "------", "------", "------",
967 "------");
968 printRow(pw, HEAP_COLUMN, "Native", memInfo.nativePss, memInfo.nativeSharedDirty,
969 memInfo.nativePrivateDirty, nativeMax, nativeAllocated, nativeFree);
970 printRow(pw, HEAP_COLUMN, "Dalvik", memInfo.dalvikPss, memInfo.dalvikSharedDirty,
971 memInfo.dalvikPrivateDirty, dalvikMax, dalvikAllocated, dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700973 int otherPss = memInfo.otherPss;
974 int otherSharedDirty = memInfo.otherSharedDirty;
975 int otherPrivateDirty = memInfo.otherPrivateDirty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700977 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Romain Guy65b345f2011-07-27 18:51:50 -0700978 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700979 memInfo.getOtherPss(i), memInfo.getOtherSharedDirty(i),
980 memInfo.getOtherPrivateDirty(i), "", "", "");
981 otherPss -= memInfo.getOtherPss(i);
982 otherSharedDirty -= memInfo.getOtherSharedDirty(i);
983 otherPrivateDirty -= memInfo.getOtherPrivateDirty(i);
984 }
985
986 printRow(pw, HEAP_COLUMN, "Unknown", otherPss, otherSharedDirty,
987 otherPrivateDirty, "", "", "");
988 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
989 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
990 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
991 nativeFree+dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992
993 pw.println(" ");
994 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -0700995 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 viewRootInstanceCount);
997
998 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
999 "Activities:", activityInstanceCount);
1000
1001 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1002 "AssetManagers:", globalAssetManagerCount);
1003
1004 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1005 "Proxy Binders:", binderProxyObjectCount);
1006 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1007
1008 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 // SQLite mem info
1011 pw.println(" ");
1012 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001013 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1014 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1015 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001016 pw.println(" ");
1017 int N = stats.dbStats.size();
1018 if (N > 0) {
1019 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -07001020 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
1021 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001022 for (int i = 0; i < N; i++) {
1023 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001024 printRow(pw, DB_INFO_FORMAT,
1025 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1026 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1027 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1028 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001029 }
1030 }
Bob Leee5408332009-09-04 18:31:17 -07001031
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001032 // Asset details.
1033 String assetAlloc = AssetManager.getAssetAllocations();
1034 if (assetAlloc != null) {
1035 pw.println(" ");
1036 pw.println(" Asset Allocations");
1037 pw.print(assetAlloc);
1038 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001039
1040 return memInfo;
1041 }
1042
1043 @Override
1044 public void dumpGfxInfo(FileDescriptor fd, String[] args) {
1045 dumpGraphicsInfo(fd);
Romain Guy65b345f2011-07-27 18:51:50 -07001046 WindowManagerImpl.getDefault().dumpGfxInfo(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048
Jeff Brown6754ba22011-12-14 20:20:01 -08001049 @Override
1050 public void dumpDbInfo(FileDescriptor fd, String[] args) {
1051 PrintWriter pw = new PrintWriter(new FileOutputStream(fd));
1052 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1053 SQLiteDebug.dump(printer, args);
1054 pw.flush();
1055 }
1056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 private void printRow(PrintWriter pw, String format, Object...objs) {
1058 pw.println(String.format(format, objs));
1059 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001060
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001061 public void setCoreSettings(Bundle coreSettings) {
1062 queueOrSendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001063 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001064
1065 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1066 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1067 ucd.pkg = pkg;
1068 ucd.info = info;
1069 queueOrSendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
1070 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001071
1072 public void scheduleTrimMemory(int level) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001073 queueOrSendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001074 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077
Romain Guy65b345f2011-07-27 18:51:50 -07001078 private class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 public static final int LAUNCH_ACTIVITY = 100;
1080 public static final int PAUSE_ACTIVITY = 101;
1081 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1082 public static final int STOP_ACTIVITY_SHOW = 103;
1083 public static final int STOP_ACTIVITY_HIDE = 104;
1084 public static final int SHOW_WINDOW = 105;
1085 public static final int HIDE_WINDOW = 106;
1086 public static final int RESUME_ACTIVITY = 107;
1087 public static final int SEND_RESULT = 108;
Brian Carlstromed7e0072011-03-24 13:27:57 -07001088 public static final int DESTROY_ACTIVITY = 109;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 public static final int BIND_APPLICATION = 110;
1090 public static final int EXIT_APPLICATION = 111;
1091 public static final int NEW_INTENT = 112;
1092 public static final int RECEIVER = 113;
1093 public static final int CREATE_SERVICE = 114;
1094 public static final int SERVICE_ARGS = 115;
1095 public static final int STOP_SERVICE = 116;
1096 public static final int REQUEST_THUMBNAIL = 117;
1097 public static final int CONFIGURATION_CHANGED = 118;
1098 public static final int CLEAN_UP_CONTEXT = 119;
1099 public static final int GC_WHEN_IDLE = 120;
1100 public static final int BIND_SERVICE = 121;
1101 public static final int UNBIND_SERVICE = 122;
1102 public static final int DUMP_SERVICE = 123;
1103 public static final int LOW_MEMORY = 124;
1104 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1105 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001106 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001107 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001108 public static final int DESTROY_BACKUP_AGENT = 129;
1109 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001110 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001111 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001112 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001113 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001114 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001115 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001116 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001117 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001118 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001119 public static final int TRIM_MEMORY = 140;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001120 public static final int DUMP_PROVIDER = 141;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001122 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 switch (code) {
1124 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1125 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1126 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1127 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1128 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1129 case SHOW_WINDOW: return "SHOW_WINDOW";
1130 case HIDE_WINDOW: return "HIDE_WINDOW";
1131 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1132 case SEND_RESULT: return "SEND_RESULT";
1133 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1134 case BIND_APPLICATION: return "BIND_APPLICATION";
1135 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1136 case NEW_INTENT: return "NEW_INTENT";
1137 case RECEIVER: return "RECEIVER";
1138 case CREATE_SERVICE: return "CREATE_SERVICE";
1139 case SERVICE_ARGS: return "SERVICE_ARGS";
1140 case STOP_SERVICE: return "STOP_SERVICE";
1141 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1142 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1143 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1144 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1145 case BIND_SERVICE: return "BIND_SERVICE";
1146 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1147 case DUMP_SERVICE: return "DUMP_SERVICE";
1148 case LOW_MEMORY: return "LOW_MEMORY";
1149 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1150 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001151 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001152 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1153 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001154 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001155 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001156 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001157 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001158 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001159 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001160 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001161 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001162 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001163 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001164 case TRIM_MEMORY: return "TRIM_MEMORY";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001165 case DUMP_PROVIDER: return "DUMP_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
1167 }
1168 return "(unknown)";
1169 }
1170 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001171 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 switch (msg.what) {
1173 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001174 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175
1176 r.packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001177 r.activityInfo.applicationInfo, r.compatInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001178 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 } break;
1180 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001181 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001182 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 } break;
1184 case PAUSE_ACTIVITY:
1185 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001186 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 break;
1188 case PAUSE_ACTIVITY_FINISHING:
1189 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1190 break;
1191 case STOP_ACTIVITY_SHOW:
1192 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1193 break;
1194 case STOP_ACTIVITY_HIDE:
1195 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1196 break;
1197 case SHOW_WINDOW:
1198 handleWindowVisibility((IBinder)msg.obj, true);
1199 break;
1200 case HIDE_WINDOW:
1201 handleWindowVisibility((IBinder)msg.obj, false);
1202 break;
1203 case RESUME_ACTIVITY:
1204 handleResumeActivity((IBinder)msg.obj, true,
1205 msg.arg1 != 0);
1206 break;
1207 case SEND_RESULT:
1208 handleSendResult((ResultData)msg.obj);
1209 break;
1210 case DESTROY_ACTIVITY:
1211 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1212 msg.arg2, false);
1213 break;
1214 case BIND_APPLICATION:
1215 AppBindData data = (AppBindData)msg.obj;
1216 handleBindApplication(data);
1217 break;
1218 case EXIT_APPLICATION:
1219 if (mInitialApplication != null) {
1220 mInitialApplication.onTerminate();
1221 }
1222 Looper.myLooper().quit();
1223 break;
1224 case NEW_INTENT:
1225 handleNewIntent((NewIntentData)msg.obj);
1226 break;
1227 case RECEIVER:
1228 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001229 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 break;
1231 case CREATE_SERVICE:
1232 handleCreateService((CreateServiceData)msg.obj);
1233 break;
1234 case BIND_SERVICE:
1235 handleBindService((BindServiceData)msg.obj);
1236 break;
1237 case UNBIND_SERVICE:
1238 handleUnbindService((BindServiceData)msg.obj);
1239 break;
1240 case SERVICE_ARGS:
1241 handleServiceArgs((ServiceArgsData)msg.obj);
1242 break;
1243 case STOP_SERVICE:
1244 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001245 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 break;
1247 case REQUEST_THUMBNAIL:
1248 handleRequestThumbnail((IBinder)msg.obj);
1249 break;
1250 case CONFIGURATION_CHANGED:
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001251 handleConfigurationChanged((Configuration)msg.obj, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 break;
1253 case CLEAN_UP_CONTEXT:
1254 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1255 cci.context.performFinalCleanup(cci.who, cci.what);
1256 break;
1257 case GC_WHEN_IDLE:
1258 scheduleGcIdler();
1259 break;
1260 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001261 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 break;
1263 case LOW_MEMORY:
1264 handleLowMemory();
1265 break;
1266 case ACTIVITY_CONFIGURATION_CHANGED:
1267 handleActivityConfigurationChanged((IBinder)msg.obj);
1268 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001269 case PROFILER_CONTROL:
Romain Guy7eabe552011-07-21 14:56:34 -07001270 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001271 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001272 case CREATE_BACKUP_AGENT:
1273 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1274 break;
1275 case DESTROY_BACKUP_AGENT:
1276 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1277 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001278 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001279 Process.killProcess(Process.myPid());
1280 break;
1281 case REMOVE_PROVIDER:
1282 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001283 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001284 case ENABLE_JIT:
1285 ensureJitEnabled();
1286 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001287 case DISPATCH_PACKAGE_BROADCAST:
1288 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1289 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001290 case SCHEDULE_CRASH:
1291 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001292 case DUMP_HEAP:
1293 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1294 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001295 case DUMP_ACTIVITY:
1296 handleDumpActivity((DumpComponentInfo)msg.obj);
1297 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001298 case DUMP_PROVIDER:
1299 handleDumpProvider((DumpComponentInfo)msg.obj);
1300 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001301 case SLEEPING:
1302 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
1303 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001304 case SET_CORE_SETTINGS:
1305 handleSetCoreSettings((Bundle) msg.obj);
1306 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001307 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1308 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001309 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001310 case TRIM_MEMORY:
1311 handleTrimMemory(msg.arg1);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001312 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001314 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
Bob Leee5408332009-09-04 18:31:17 -07001316
Brian Carlstromed7e0072011-03-24 13:27:57 -07001317 private void maybeSnapshot() {
1318 if (mBoundApplication != null && SamplingProfilerIntegration.isEnabled()) {
Sen Hubde75702010-05-28 01:54:03 -07001319 // convert the *private* ActivityThread.PackageInfo to *public* known
1320 // android.content.pm.PackageInfo
1321 String packageName = mBoundApplication.info.mPackageName;
1322 android.content.pm.PackageInfo packageInfo = null;
1323 try {
1324 Context context = getSystemContext();
1325 if(context == null) {
1326 Log.e(TAG, "cannot get a valid context");
1327 return;
1328 }
1329 PackageManager pm = context.getPackageManager();
1330 if(pm == null) {
1331 Log.e(TAG, "cannot get a valid PackageManager");
1332 return;
1333 }
1334 packageInfo = pm.getPackageInfo(
1335 packageName, PackageManager.GET_ACTIVITIES);
1336 } catch (NameNotFoundException e) {
1337 Log.e(TAG, "cannot get package info for " + packageName, e);
1338 }
1339 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001340 }
1341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 }
1343
Romain Guy65b345f2011-07-27 18:51:50 -07001344 private class Idler implements MessageQueue.IdleHandler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001346 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001347 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001348 if (mBoundApplication != null && mProfiler.profileFd != null
1349 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001350 stopProfiling = true;
1351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 if (a != null) {
1353 mNewActivities = null;
1354 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001355 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001357 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 TAG, "Reporting idle of " + a +
1359 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001360 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 if (a.activity != null && !a.activity.mFinished) {
1362 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001363 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001364 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07001366 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
1368 }
1369 prev = a;
1370 a = a.nextIdle;
1371 prev.nextIdle = null;
1372 } while (a != null);
1373 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001374 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001375 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001376 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001377 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 return false;
1379 }
1380 }
1381
1382 final class GcIdler implements MessageQueue.IdleHandler {
1383 public final boolean queueIdle() {
1384 doGcIfNeeded();
1385 return false;
1386 }
1387 }
1388
Romain Guy65b345f2011-07-27 18:51:50 -07001389 private static class ResourcesKey {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001390 final private String mResDir;
1391 final private float mScale;
1392 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001393
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001394 ResourcesKey(String resDir, float scale) {
1395 mResDir = resDir;
1396 mScale = scale;
1397 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1398 }
Bob Leee5408332009-09-04 18:31:17 -07001399
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001400 @Override
1401 public int hashCode() {
1402 return mHash;
1403 }
1404
1405 @Override
1406 public boolean equals(Object obj) {
1407 if (!(obj instanceof ResourcesKey)) {
1408 return false;
1409 }
1410 ResourcesKey peer = (ResourcesKey) obj;
1411 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1412 }
1413 }
1414
Romain Guy65b345f2011-07-27 18:51:50 -07001415 public static ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001416 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418
Romain Guy65b345f2011-07-27 18:51:50 -07001419 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001420 ActivityThread am = currentActivityThread();
1421 return (am != null && am.mBoundApplication != null)
1422 ? am.mBoundApplication.processName : null;
1423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424
Romain Guy65b345f2011-07-27 18:51:50 -07001425 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001426 ActivityThread am = currentActivityThread();
1427 return am != null ? am.mInitialApplication : null;
1428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001430 public static IPackageManager getPackageManager() {
1431 if (sPackageManager != null) {
1432 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1433 return sPackageManager;
1434 }
1435 IBinder b = ServiceManager.getService("package");
1436 //Slog.v("PackageManager", "default service binder = " + b);
1437 sPackageManager = IPackageManager.Stub.asInterface(b);
1438 //Slog.v("PackageManager", "default service = " + sPackageManager);
1439 return sPackageManager;
1440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001442 DisplayMetrics getDisplayMetricsLocked(CompatibilityInfo ci, boolean forceUpdate) {
1443 DisplayMetrics dm = mDisplayMetrics.get(ci);
1444 if (dm != null && !forceUpdate) {
1445 return dm;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001446 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001447 if (dm == null) {
1448 dm = new DisplayMetrics();
1449 mDisplayMetrics.put(ci, dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001450 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001451 Display d = WindowManagerImpl.getDefault(ci).getDefaultDisplay();
1452 d.getMetrics(dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001453 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1454 // + metrics.heightPixels + " den=" + metrics.density
1455 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001456 return dm;
1457 }
1458
1459 static Configuration applyConfigCompat(Configuration config, CompatibilityInfo compat) {
1460 if (config == null) {
1461 return null;
1462 }
1463 if (compat != null && !compat.supportsScreen()) {
1464 config = new Configuration(config);
1465 compat.applyToConfiguration(config);
1466 }
1467 return config;
1468 }
1469
Romain Guy65b345f2011-07-27 18:51:50 -07001470 private Configuration mMainThreadConfig = new Configuration();
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001471 Configuration applyConfigCompatMainThread(Configuration config, CompatibilityInfo compat) {
1472 if (config == null) {
1473 return null;
1474 }
1475 if (compat != null && !compat.supportsScreen()) {
1476 mMainThreadConfig.setTo(config);
1477 config = mMainThreadConfig;
1478 compat.applyToConfiguration(config);
1479 }
1480 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001483 /**
1484 * Creates the top level Resources for applications with the given compatibility info.
1485 *
1486 * @param resDir the resource directory.
1487 * @param compInfo the compability info. It will use the default compatibility info when it's
1488 * null.
1489 */
1490 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1491 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1492 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001494 // Resources is app scale dependent.
1495 if (false) {
1496 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1497 + compInfo.applicationScale);
1498 }
1499 WeakReference<Resources> wr = mActiveResources.get(key);
1500 r = wr != null ? wr.get() : null;
1501 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1502 if (r != null && r.getAssets().isUpToDate()) {
1503 if (false) {
1504 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1505 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1506 }
1507 return r;
1508 }
1509 }
1510
1511 //if (r != null) {
1512 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1513 // + r + " " + resDir);
1514 //}
1515
1516 AssetManager assets = new AssetManager();
1517 if (assets.addAssetPath(resDir) == 0) {
1518 return null;
1519 }
1520
1521 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Dianne Hackborn836e2622011-10-04 18:32:39 -07001522 DisplayMetrics metrics = getDisplayMetricsLocked(null, false);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001523 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1524 if (false) {
1525 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1526 + r.getConfiguration() + " appScale="
1527 + r.getCompatibilityInfo().applicationScale);
1528 }
1529
1530 synchronized (mPackages) {
1531 WeakReference<Resources> wr = mActiveResources.get(key);
1532 Resources existing = wr != null ? wr.get() : null;
1533 if (existing != null && existing.getAssets().isUpToDate()) {
1534 // Someone else already created the resources while we were
1535 // unlocked; go ahead and use theirs.
1536 r.getAssets().close();
1537 return existing;
1538 }
1539
1540 // XXX need to remove entries when weak references go away
1541 mActiveResources.put(key, new WeakReference<Resources>(r));
1542 return r;
1543 }
1544 }
1545
1546 /**
1547 * Creates the top level resources for the given package.
1548 */
1549 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001550 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo.get());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001551 }
1552
1553 final Handler getHandler() {
1554 return mH;
1555 }
1556
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001557 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1558 int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001559 synchronized (mPackages) {
1560 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1562 ref = mPackages.get(packageName);
1563 } else {
1564 ref = mResourcePackages.get(packageName);
1565 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001566 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001567 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001568 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1569 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 if (packageInfo != null && (packageInfo.mResources == null
1571 || packageInfo.mResources.getAssets().isUpToDate())) {
1572 if (packageInfo.isSecurityViolation()
1573 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1574 throw new SecurityException(
1575 "Requesting code from " + packageName
1576 + " to be run in process "
1577 + mBoundApplication.processName
1578 + "/" + mBoundApplication.appInfo.uid);
1579 }
1580 return packageInfo;
1581 }
1582 }
1583
1584 ApplicationInfo ai = null;
1585 try {
1586 ai = getPackageManager().getApplicationInfo(packageName,
1587 PackageManager.GET_SHARED_LIBRARY_FILES);
1588 } catch (RemoteException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07001589 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 }
1591
1592 if (ai != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001593 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
1595
1596 return null;
1597 }
1598
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001599 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
1600 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1602 boolean securityViolation = includeCode && ai.uid != 0
1603 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Amith Yamasani742a6712011-05-04 14:49:28 -07001604 ? !UserId.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
1605 : true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1607 |Context.CONTEXT_IGNORE_SECURITY))
1608 == Context.CONTEXT_INCLUDE_CODE) {
1609 if (securityViolation) {
1610 String msg = "Requesting code from " + ai.packageName
1611 + " (with uid " + ai.uid + ")";
1612 if (mBoundApplication != null) {
1613 msg = msg + " to be run in process "
1614 + mBoundApplication.processName + " (with uid "
1615 + mBoundApplication.appInfo.uid + ")";
1616 }
1617 throw new SecurityException(msg);
1618 }
1619 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001620 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 }
1622
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001623 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
1624 CompatibilityInfo compatInfo) {
1625 return getPackageInfo(ai, compatInfo, null, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001628 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
1629 synchronized (mPackages) {
1630 WeakReference<LoadedApk> ref;
1631 if (includeCode) {
1632 ref = mPackages.get(packageName);
1633 } else {
1634 ref = mResourcePackages.get(packageName);
1635 }
1636 return ref != null ? ref.get() : null;
1637 }
1638 }
1639
Romain Guy65b345f2011-07-27 18:51:50 -07001640 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1642 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001643 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 if (includeCode) {
1645 ref = mPackages.get(aInfo.packageName);
1646 } else {
1647 ref = mResourcePackages.get(aInfo.packageName);
1648 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001649 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 if (packageInfo == null || (packageInfo.mResources != null
1651 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001652 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 : "Loading resource-only package ") + aInfo.packageName
1654 + " (in " + (mBoundApplication != null
1655 ? mBoundApplication.processName : null)
1656 + ")");
1657 packageInfo =
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001658 new LoadedApk(this, aInfo, compatInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 securityViolation, includeCode &&
1660 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1661 if (includeCode) {
1662 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001663 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 } else {
1665 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001666 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
1668 }
1669 return packageInfo;
1670 }
1671 }
1672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 ActivityThread() {
1674 }
1675
1676 public ApplicationThread getApplicationThread()
1677 {
1678 return mAppThread;
1679 }
1680
1681 public Instrumentation getInstrumentation()
1682 {
1683 return mInstrumentation;
1684 }
1685
1686 public Configuration getConfiguration() {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001687 return mResConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689
1690 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001691 return mProfiler != null && mProfiler.profileFile != null
1692 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694
1695 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001696 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698
1699 public Looper getLooper() {
1700 return mLooper;
1701 }
1702
1703 public Application getApplication() {
1704 return mInitialApplication;
1705 }
Bob Leee5408332009-09-04 18:31:17 -07001706
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001707 public String getProcessName() {
1708 return mBoundApplication.processName;
1709 }
Bob Leee5408332009-09-04 18:31:17 -07001710
Dianne Hackborn21556372010-02-04 16:34:40 -08001711 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 synchronized (this) {
1713 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001714 ContextImpl context =
1715 ContextImpl.createSystemContext(this);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001716 LoadedApk info = new LoadedApk(this, "android", context, null,
1717 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 context.init(info, null, this);
1719 context.getResources().updateConfiguration(
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001720 getConfiguration(), getDisplayMetricsLocked(
1721 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001723 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 // + ": " + context.getResources().getConfiguration());
1725 }
1726 }
1727 return mSystemContext;
1728 }
1729
Mike Cleron432b7132009-09-24 15:28:29 -07001730 public void installSystemApplicationInfo(ApplicationInfo info) {
1731 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001732 ContextImpl context = getSystemContext();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001733 context.init(new LoadedApk(this, "android", context, info,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001734 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO), null, this);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001735
1736 // give ourselves a default profiler
1737 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07001738 }
1739 }
1740
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001741 void ensureJitEnabled() {
1742 if (!mJitEnabled) {
1743 mJitEnabled = true;
1744 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1745 }
1746 }
1747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 void scheduleGcIdler() {
1749 if (!mGcIdlerScheduled) {
1750 mGcIdlerScheduled = true;
1751 Looper.myQueue().addIdleHandler(mGcIdler);
1752 }
1753 mH.removeMessages(H.GC_WHEN_IDLE);
1754 }
1755
1756 void unscheduleGcIdler() {
1757 if (mGcIdlerScheduled) {
1758 mGcIdlerScheduled = false;
1759 Looper.myQueue().removeIdleHandler(mGcIdler);
1760 }
1761 mH.removeMessages(H.GC_WHEN_IDLE);
1762 }
1763
1764 void doGcIfNeeded() {
1765 mGcIdlerScheduled = false;
1766 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001767 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 // + "m now=" + now);
1769 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001770 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 BinderInternal.forceGc("bg");
1772 }
1773 }
1774
Jeff Hamilton52d32032011-01-08 15:31:26 -06001775 public void registerOnActivityPausedListener(Activity activity,
1776 OnActivityPausedListener listener) {
1777 synchronized (mOnPauseListeners) {
1778 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1779 if (list == null) {
1780 list = new ArrayList<OnActivityPausedListener>();
1781 mOnPauseListeners.put(activity, list);
1782 }
1783 list.add(listener);
1784 }
1785 }
1786
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08001787 public void unregisterOnActivityPausedListener(Activity activity,
1788 OnActivityPausedListener listener) {
1789 synchronized (mOnPauseListeners) {
1790 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1791 if (list != null) {
1792 list.remove(listener);
1793 }
1794 }
1795 }
1796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 public final ActivityInfo resolveActivityInfo(Intent intent) {
1798 ActivityInfo aInfo = intent.resolveActivityInfo(
1799 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1800 if (aInfo == null) {
1801 // Throw an exception.
1802 Instrumentation.checkStartActivityResult(
1803 IActivityManager.START_CLASS_NOT_FOUND, intent);
1804 }
1805 return aInfo;
1806 }
Bob Leee5408332009-09-04 18:31:17 -07001807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001810 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001811 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001813 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 r.intent = intent;
1815 r.state = state;
1816 r.parent = parent;
1817 r.embeddedID = id;
1818 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001819 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 if (localLOGV) {
1821 ComponentName compname = intent.getComponent();
1822 String name;
1823 if (compname != null) {
1824 name = compname.toShortString();
1825 } else {
1826 name = "(Intent " + intent + ").getComponent() returned null";
1827 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001828 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 + ", comp=" + name
1830 + ", token=" + token);
1831 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001832 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
1834
1835 public final Activity getActivity(IBinder token) {
1836 return mActivities.get(token).activity;
1837 }
1838
1839 public final void sendActivityResult(
1840 IBinder token, String id, int requestCode,
1841 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001842 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001843 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1845 list.add(new ResultInfo(id, requestCode, resultCode, data));
1846 mAppThread.scheduleSendResult(token, list);
1847 }
1848
1849 // if the thread hasn't started yet, we don't have the handler, so just
1850 // save the messages until we're ready.
Romain Guy65b345f2011-07-27 18:51:50 -07001851 private void queueOrSendMessage(int what, Object obj) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 queueOrSendMessage(what, obj, 0, 0);
1853 }
1854
Romain Guy65b345f2011-07-27 18:51:50 -07001855 private void queueOrSendMessage(int what, Object obj, int arg1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 queueOrSendMessage(what, obj, arg1, 0);
1857 }
1858
Romain Guy65b345f2011-07-27 18:51:50 -07001859 private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001861 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1863 + ": " + arg1 + " / " + obj);
1864 Message msg = Message.obtain();
1865 msg.what = what;
1866 msg.obj = obj;
1867 msg.arg1 = arg1;
1868 msg.arg2 = arg2;
1869 mH.sendMessage(msg);
1870 }
1871 }
1872
Dianne Hackborn21556372010-02-04 16:34:40 -08001873 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 String what) {
1875 ContextCleanupInfo cci = new ContextCleanupInfo();
1876 cci.context = context;
1877 cci.who = who;
1878 cci.what = what;
1879 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1880 }
1881
Romain Guy65b345f2011-07-27 18:51:50 -07001882 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1884
1885 ActivityInfo aInfo = r.activityInfo;
1886 if (r.packageInfo == null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001887 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 Context.CONTEXT_INCLUDE_CODE);
1889 }
Bob Leee5408332009-09-04 18:31:17 -07001890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 ComponentName component = r.intent.getComponent();
1892 if (component == null) {
1893 component = r.intent.resolveActivity(
1894 mInitialApplication.getPackageManager());
1895 r.intent.setComponent(component);
1896 }
1897
1898 if (r.activityInfo.targetActivity != null) {
1899 component = new ComponentName(r.activityInfo.packageName,
1900 r.activityInfo.targetActivity);
1901 }
1902
1903 Activity activity = null;
1904 try {
1905 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1906 activity = mInstrumentation.newActivity(
1907 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001908 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 r.intent.setExtrasClassLoader(cl);
1910 if (r.state != null) {
1911 r.state.setClassLoader(cl);
1912 }
1913 } catch (Exception e) {
1914 if (!mInstrumentation.onException(activity, e)) {
1915 throw new RuntimeException(
1916 "Unable to instantiate activity " + component
1917 + ": " + e.toString(), e);
1918 }
1919 }
1920
1921 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001922 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001923
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001924 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1925 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 TAG, r + ": app=" + app
1927 + ", appName=" + app.getPackageName()
1928 + ", pkg=" + r.packageInfo.getPackageName()
1929 + ", comp=" + r.intent.getComponent().toShortString()
1930 + ", dir=" + r.packageInfo.getAppDir());
1931
1932 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001933 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 appContext.init(r.packageInfo, r.token, this);
1935 appContext.setOuterContext(activity);
1936 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001937 Configuration config = new Configuration(mCompatConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001938 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001939 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001940 activity.attach(appContext, this, getInstrumentation(), r.token,
1941 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001942 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001943
Christopher Tateb70f3df2009-04-07 16:07:59 -07001944 if (customIntent != null) {
1945 activity.mIntent = customIntent;
1946 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001947 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 activity.mStartedActivity = false;
1949 int theme = r.activityInfo.getThemeResource();
1950 if (theme != 0) {
1951 activity.setTheme(theme);
1952 }
1953
1954 activity.mCalled = false;
1955 mInstrumentation.callActivityOnCreate(activity, r.state);
1956 if (!activity.mCalled) {
1957 throw new SuperNotCalledException(
1958 "Activity " + r.intent.getComponent().toShortString() +
1959 " did not call through to super.onCreate()");
1960 }
1961 r.activity = activity;
1962 r.stopped = true;
1963 if (!r.activity.mFinished) {
1964 activity.performStart();
1965 r.stopped = false;
1966 }
1967 if (!r.activity.mFinished) {
1968 if (r.state != null) {
1969 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1970 }
1971 }
1972 if (!r.activity.mFinished) {
1973 activity.mCalled = false;
1974 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1975 if (!activity.mCalled) {
1976 throw new SuperNotCalledException(
1977 "Activity " + r.intent.getComponent().toShortString() +
1978 " did not call through to super.onPostCreate()");
1979 }
1980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 }
1982 r.paused = true;
1983
1984 mActivities.put(r.token, r);
1985
1986 } catch (SuperNotCalledException e) {
1987 throw e;
1988
1989 } catch (Exception e) {
1990 if (!mInstrumentation.onException(activity, e)) {
1991 throw new RuntimeException(
1992 "Unable to start activity " + component
1993 + ": " + e.toString(), e);
1994 }
1995 }
1996
1997 return activity;
1998 }
1999
Romain Guy65b345f2011-07-27 18:51:50 -07002000 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 // If we are getting ready to gc after going to the background, well
2002 // we are back active so skip it.
2003 unscheduleGcIdler();
2004
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002005 if (r.profileFd != null) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002006 mProfiler.setProfiler(r.profileFile, r.profileFd);
2007 mProfiler.startProfiling();
2008 mProfiler.autoStopProfiler = r.autoStopProfiler;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002009 }
2010
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002011 // Make sure we are running with the most recent config.
2012 handleConfigurationChanged(null, null);
2013
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002014 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002016 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017
2018 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002019 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002020 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 handleResumeActivity(r.token, false, r.isForward);
2022
2023 if (!r.activity.mFinished && r.startsNotResumed) {
2024 // The activity manager actually wants this one to start out
2025 // paused, because it needs to be visible but isn't in the
2026 // foreground. We accomplish this by going through the
2027 // normal startup (because activities expect to go through
2028 // onResume() the first time they run, before their window
2029 // is displayed), and then pausing it. However, in this case
2030 // we do -not- need to do the full pause cycle (of freezing
2031 // and such) because the activity manager assumes it can just
2032 // retain the current state it has.
2033 try {
2034 r.activity.mCalled = false;
2035 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002036 // We need to keep around the original state, in case
2037 // we need to be created again.
2038 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 if (!r.activity.mCalled) {
2040 throw new SuperNotCalledException(
2041 "Activity " + r.intent.getComponent().toShortString() +
2042 " did not call through to super.onPause()");
2043 }
2044
2045 } catch (SuperNotCalledException e) {
2046 throw e;
2047
2048 } catch (Exception e) {
2049 if (!mInstrumentation.onException(r.activity, e)) {
2050 throw new RuntimeException(
2051 "Unable to pause activity "
2052 + r.intent.getComponent().toShortString()
2053 + ": " + e.toString(), e);
2054 }
2055 }
2056 r.paused = true;
2057 }
2058 } else {
2059 // If there was an error, for any reason, tell the activity
2060 // manager to stop us.
2061 try {
2062 ActivityManagerNative.getDefault()
2063 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2064 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07002065 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
2067 }
2068 }
2069
Romain Guy65b345f2011-07-27 18:51:50 -07002070 private void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 List<Intent> intents) {
2072 final int N = intents.size();
2073 for (int i=0; i<N; i++) {
2074 Intent intent = intents.get(i);
2075 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002076 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2078 }
2079 }
2080
2081 public final void performNewIntents(IBinder token,
2082 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002083 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 if (r != null) {
2085 final boolean resumed = !r.paused;
2086 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002087 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 mInstrumentation.callActivityOnPause(r.activity);
2089 }
2090 deliverNewIntents(r, intents);
2091 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07002092 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002093 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 }
2095 }
2096 }
Bob Leee5408332009-09-04 18:31:17 -07002097
Romain Guy65b345f2011-07-27 18:51:50 -07002098 private void handleNewIntent(NewIntentData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 performNewIntents(data.token, data.intents);
2100 }
2101
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002102 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
2103
2104 /**
2105 * Return the Intent that's currently being handled by a
2106 * BroadcastReceiver on this thread, or null if none.
2107 * @hide
2108 */
2109 public static Intent getIntentBeingBroadcast() {
2110 return sCurrentBroadcastIntent.get();
2111 }
2112
Romain Guy65b345f2011-07-27 18:51:50 -07002113 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 // If we are getting ready to gc after going to the background, well
2115 // we are back active so skip it.
2116 unscheduleGcIdler();
2117
2118 String component = data.intent.getComponent().getClassName();
2119
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002120 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002121 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122
2123 IActivityManager mgr = ActivityManagerNative.getDefault();
2124
Romain Guy65b345f2011-07-27 18:51:50 -07002125 BroadcastReceiver receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 try {
2127 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2128 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002129 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2131 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002132 if (DEBUG_BROADCAST) Slog.i(TAG,
2133 "Finishing failed broadcast to " + data.intent.getComponent());
2134 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 throw new RuntimeException(
2136 "Unable to instantiate receiver " + component
2137 + ": " + e.toString(), e);
2138 }
2139
2140 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002141 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002142
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002143 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 TAG, "Performing receive of " + data.intent
2145 + ": app=" + app
2146 + ", appName=" + app.getPackageName()
2147 + ", pkg=" + packageInfo.getPackageName()
2148 + ", comp=" + data.intent.getComponent().toShortString()
2149 + ", dir=" + packageInfo.getAppDir());
2150
Dianne Hackborn21556372010-02-04 16:34:40 -08002151 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002152 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002153 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 receiver.onReceive(context.getReceiverRestrictedContext(),
2155 data.intent);
2156 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002157 if (DEBUG_BROADCAST) Slog.i(TAG,
2158 "Finishing failed broadcast to " + data.intent.getComponent());
2159 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 if (!mInstrumentation.onException(receiver, e)) {
2161 throw new RuntimeException(
2162 "Unable to start receiver " + component
2163 + ": " + e.toString(), e);
2164 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002165 } finally {
2166 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 }
2168
Dianne Hackborne829fef2010-10-26 17:44:01 -07002169 if (receiver.getPendingResult() != null) {
2170 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 }
2172 }
2173
Christopher Tate181fafa2009-05-14 11:12:14 -07002174 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07002175 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002176 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002177
2178 // no longer idle; we have backup work to do
2179 unscheduleGcIdler();
2180
2181 // instantiate the BackupAgent class named in the manifest
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002182 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002183 String packageName = packageInfo.mPackageName;
2184 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002185 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07002186 + " already exists");
2187 return;
2188 }
Bob Leee5408332009-09-04 18:31:17 -07002189
Christopher Tate181fafa2009-05-14 11:12:14 -07002190 BackupAgent agent = null;
2191 String classname = data.appInfo.backupAgentName;
Christopher Tate4a627c72011-04-01 14:43:32 -07002192
Christopher Tate79ec80d2011-06-24 14:58:49 -07002193 // full backup operation but no app-supplied agent? use the default implementation
2194 if (classname == null && (data.backupMode == IApplicationThread.BACKUP_MODE_FULL
2195 || data.backupMode == IApplicationThread.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002196 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07002197 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002198
Christopher Tate181fafa2009-05-14 11:12:14 -07002199 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002200 IBinder binder = null;
2201 try {
Christopher Tate4a627c72011-04-01 14:43:32 -07002202 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
2203
Christopher Tated1475e02009-07-09 15:36:17 -07002204 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Christopher Tate4a627c72011-04-01 14:43:32 -07002205 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tated1475e02009-07-09 15:36:17 -07002206
2207 // set up the agent's context
Dianne Hackborn21556372010-02-04 16:34:40 -08002208 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07002209 context.init(packageInfo, null, this);
2210 context.setOuterContext(agent);
2211 agent.attach(context);
2212
2213 agent.onCreate();
2214 binder = agent.onBind();
2215 mBackupAgents.put(packageName, agent);
2216 } catch (Exception e) {
2217 // If this is during restore, fail silently; otherwise go
2218 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002219 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tate75a99702011-05-18 16:28:19 -07002220 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE
2221 && data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE_FULL) {
Christopher Tated1475e02009-07-09 15:36:17 -07002222 throw e;
2223 }
2224 // falling through with 'binder' still null
2225 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002226
2227 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002228 try {
2229 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2230 } catch (RemoteException e) {
2231 // nothing to do.
2232 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002233 } catch (Exception e) {
2234 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07002235 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07002236 }
2237 }
2238
2239 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07002240 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002241 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002242
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002243 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002244 String packageName = packageInfo.mPackageName;
2245 BackupAgent agent = mBackupAgents.get(packageName);
2246 if (agent != null) {
2247 try {
2248 agent.onDestroy();
2249 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002250 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002251 e.printStackTrace();
2252 }
2253 mBackupAgents.remove(packageName);
2254 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002255 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002256 }
2257 }
2258
Romain Guy65b345f2011-07-27 18:51:50 -07002259 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 // If we are getting ready to gc after going to the background, well
2261 // we are back active so skip it.
2262 unscheduleGcIdler();
2263
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002264 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002265 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 Service service = null;
2267 try {
2268 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2269 service = (Service) cl.loadClass(data.info.name).newInstance();
2270 } catch (Exception e) {
2271 if (!mInstrumentation.onException(service, e)) {
2272 throw new RuntimeException(
2273 "Unable to instantiate service " + data.info.name
2274 + ": " + e.toString(), e);
2275 }
2276 }
2277
2278 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002279 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280
Dianne Hackborn21556372010-02-04 16:34:40 -08002281 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 context.init(packageInfo, null, this);
2283
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002284 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 context.setOuterContext(service);
2286 service.attach(context, this, data.info.name, data.token, app,
2287 ActivityManagerNative.getDefault());
2288 service.onCreate();
2289 mServices.put(data.token, service);
2290 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002291 ActivityManagerNative.getDefault().serviceDoneExecuting(
2292 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 } catch (RemoteException e) {
2294 // nothing to do.
2295 }
2296 } catch (Exception e) {
2297 if (!mInstrumentation.onException(service, e)) {
2298 throw new RuntimeException(
2299 "Unable to create service " + data.info.name
2300 + ": " + e.toString(), e);
2301 }
2302 }
2303 }
2304
Romain Guy65b345f2011-07-27 18:51:50 -07002305 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07002307 if (DEBUG_SERVICE)
2308 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 if (s != null) {
2310 try {
2311 data.intent.setExtrasClassLoader(s.getClassLoader());
2312 try {
2313 if (!data.rebind) {
2314 IBinder binder = s.onBind(data.intent);
2315 ActivityManagerNative.getDefault().publishService(
2316 data.token, data.intent, binder);
2317 } else {
2318 s.onRebind(data.intent);
2319 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002320 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002322 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 } catch (RemoteException ex) {
2324 }
2325 } catch (Exception e) {
2326 if (!mInstrumentation.onException(s, e)) {
2327 throw new RuntimeException(
2328 "Unable to bind to service " + s
2329 + " with " + data.intent + ": " + e.toString(), e);
2330 }
2331 }
2332 }
2333 }
2334
Romain Guy65b345f2011-07-27 18:51:50 -07002335 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 Service s = mServices.get(data.token);
2337 if (s != null) {
2338 try {
2339 data.intent.setExtrasClassLoader(s.getClassLoader());
2340 boolean doRebind = s.onUnbind(data.intent);
2341 try {
2342 if (doRebind) {
2343 ActivityManagerNative.getDefault().unbindFinished(
2344 data.token, data.intent, doRebind);
2345 } else {
2346 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002347 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 }
2349 } catch (RemoteException ex) {
2350 }
2351 } catch (Exception e) {
2352 if (!mInstrumentation.onException(s, e)) {
2353 throw new RuntimeException(
2354 "Unable to unbind to service " + s
2355 + " with " + data.intent + ": " + e.toString(), e);
2356 }
2357 }
2358 }
2359 }
2360
Dianne Hackborn625ac272010-09-17 18:29:22 -07002361 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002362 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2363 try {
2364 Service s = mServices.get(info.token);
2365 if (s != null) {
2366 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2367 s.dump(info.fd.getFileDescriptor(), pw, info.args);
2368 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002370 } finally {
2371 IoUtils.closeQuietly(info.fd);
2372 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 }
2374 }
2375
Dianne Hackborn625ac272010-09-17 18:29:22 -07002376 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002377 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2378 try {
2379 ActivityClientRecord r = mActivities.get(info.token);
2380 if (r != null && r.activity != null) {
2381 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2382 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
2383 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07002384 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002385 } finally {
2386 IoUtils.closeQuietly(info.fd);
2387 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07002388 }
2389 }
2390
Marco Nelissen18cb2872011-11-15 11:19:53 -08002391 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002392 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2393 try {
2394 ProviderClientRecord r = mLocalProviders.get(info.token);
2395 if (r != null && r.mLocalProvider != null) {
2396 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2397 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
2398 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08002399 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002400 } finally {
2401 IoUtils.closeQuietly(info.fd);
2402 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08002403 }
2404 }
2405
Romain Guy65b345f2011-07-27 18:51:50 -07002406 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 Service s = mServices.get(data.token);
2408 if (s != null) {
2409 try {
2410 if (data.args != null) {
2411 data.args.setExtrasClassLoader(s.getClassLoader());
2412 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002413 int res;
2414 if (!data.taskRemoved) {
2415 res = s.onStartCommand(data.args, data.flags, data.startId);
2416 } else {
2417 s.onTaskRemoved(data.args);
2418 res = Service.START_TASK_REMOVED_COMPLETE;
2419 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002420
2421 QueuedWork.waitToFinish();
2422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002424 ActivityManagerNative.getDefault().serviceDoneExecuting(
2425 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 } catch (RemoteException e) {
2427 // nothing to do.
2428 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002429 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 } catch (Exception e) {
2431 if (!mInstrumentation.onException(s, e)) {
2432 throw new RuntimeException(
2433 "Unable to start service " + s
2434 + " with " + data.args + ": " + e.toString(), e);
2435 }
2436 }
2437 }
2438 }
2439
Romain Guy65b345f2011-07-27 18:51:50 -07002440 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 Service s = mServices.remove(token);
2442 if (s != null) {
2443 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002444 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 s.onDestroy();
2446 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002447 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002449 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002451
2452 QueuedWork.waitToFinish();
2453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002455 ActivityManagerNative.getDefault().serviceDoneExecuting(
2456 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 } catch (RemoteException e) {
2458 // nothing to do.
2459 }
2460 } catch (Exception e) {
2461 if (!mInstrumentation.onException(s, e)) {
2462 throw new RuntimeException(
2463 "Unable to stop service " + s
2464 + ": " + e.toString(), e);
2465 }
2466 }
2467 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002468 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 }
2470
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002471 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002473 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002474 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 + " finished=" + r.activity.mFinished);
2476 if (r != null && !r.activity.mFinished) {
2477 if (clearHide) {
2478 r.hideForNow = false;
2479 r.activity.mStartedActivity = false;
2480 }
2481 try {
2482 if (r.pendingIntents != null) {
2483 deliverNewIntents(r, r.pendingIntents);
2484 r.pendingIntents = null;
2485 }
2486 if (r.pendingResults != null) {
2487 deliverResults(r, r.pendingResults);
2488 r.pendingResults = null;
2489 }
2490 r.activity.performResume();
2491
Bob Leee5408332009-09-04 18:31:17 -07002492 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 r.paused = false;
2496 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 r.state = null;
2498 } catch (Exception e) {
2499 if (!mInstrumentation.onException(r.activity, e)) {
2500 throw new RuntimeException(
2501 "Unable to resume activity "
2502 + r.intent.getComponent().toShortString()
2503 + ": " + e.toString(), e);
2504 }
2505 }
2506 }
2507 return r;
2508 }
2509
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002510 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
2511 if (r.mPendingRemoveWindow != null) {
2512 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2513 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2514 if (wtoken != null) {
2515 WindowManagerImpl.getDefault().closeAll(wtoken,
2516 r.activity.getClass().getName(), "Activity");
2517 }
2518 }
2519 r.mPendingRemoveWindow = null;
2520 r.mPendingRemoveWindowManager = null;
2521 }
2522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2524 // If we are getting ready to gc after going to the background, well
2525 // we are back active so skip it.
2526 unscheduleGcIdler();
2527
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002528 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529
2530 if (r != null) {
2531 final Activity a = r.activity;
2532
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002533 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 TAG, "Resume " + r + " started activity: " +
2535 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2536 + ", finished: " + a.mFinished);
2537
2538 final int forwardBit = isForward ?
2539 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 // If the window hasn't yet been added to the window manager,
2542 // and this guy didn't finish itself or start another activity,
2543 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002544 boolean willBeVisible = !a.mStartedActivity;
2545 if (!willBeVisible) {
2546 try {
2547 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2548 a.getActivityToken());
2549 } catch (RemoteException e) {
2550 }
2551 }
2552 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 r.window = r.activity.getWindow();
2554 View decor = r.window.getDecorView();
2555 decor.setVisibility(View.INVISIBLE);
2556 ViewManager wm = a.getWindowManager();
2557 WindowManager.LayoutParams l = r.window.getAttributes();
2558 a.mDecor = decor;
2559 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2560 l.softInputMode |= forwardBit;
2561 if (a.mVisibleFromClient) {
2562 a.mWindowAdded = true;
2563 wm.addView(decor, l);
2564 }
2565
2566 // If the window has already been added, but during resume
2567 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002568 // window visible.
2569 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002570 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 TAG, "Launch " + r + " mStartedActivity set");
2572 r.hideForNow = true;
2573 }
2574
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002575 // Get rid of anything left hanging around.
2576 cleanUpPendingRemoveWindows(r);
2577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 // The window is now visible if it has been added, we are not
2579 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002580 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002581 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002583 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002584 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 performConfigurationChanged(r.activity, r.newConfig);
2586 r.newConfig = null;
2587 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002588 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 + isForward);
2590 WindowManager.LayoutParams l = r.window.getAttributes();
2591 if ((l.softInputMode
2592 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2593 != forwardBit) {
2594 l.softInputMode = (l.softInputMode
2595 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2596 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002597 if (r.activity.mVisibleFromClient) {
2598 ViewManager wm = a.getWindowManager();
2599 View decor = r.window.getDecorView();
2600 wm.updateViewLayout(decor, l);
2601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 }
2603 r.activity.mVisibleFromServer = true;
2604 mNumVisibleActivities++;
2605 if (r.activity.mVisibleFromClient) {
2606 r.activity.makeVisible();
2607 }
2608 }
2609
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002610 if (!r.onlyLocalRequest) {
2611 r.nextIdle = mNewActivities;
2612 mNewActivities = r;
2613 if (localLOGV) Slog.v(
2614 TAG, "Scheduling idle handler for " + r);
2615 Looper.myQueue().addIdleHandler(new Idler());
2616 }
2617 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618
2619 } else {
2620 // If an exception was thrown when trying to resume, then
2621 // just end this activity.
2622 try {
2623 ActivityManagerNative.getDefault()
2624 .finishActivity(token, Activity.RESULT_CANCELED, null);
2625 } catch (RemoteException ex) {
2626 }
2627 }
2628 }
2629
2630 private int mThumbnailWidth = -1;
2631 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002632 private Bitmap mAvailThumbnailBitmap = null;
2633 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634
Romain Guy65b345f2011-07-27 18:51:50 -07002635 private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002636 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002638 if (thumbnail == null) {
2639 int w = mThumbnailWidth;
2640 int h;
2641 if (w < 0) {
2642 Resources res = r.activity.getResources();
2643 mThumbnailHeight = h =
2644 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002646 mThumbnailWidth = w =
2647 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2648 } else {
2649 h = mThumbnailHeight;
2650 }
2651
2652 // On platforms where we don't want thumbnails, set dims to (0,0)
2653 if ((w > 0) && (h > 0)) {
2654 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2655 thumbnail.eraseColor(0);
2656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 }
2658
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002659 if (thumbnail != null) {
2660 Canvas cv = mThumbnailCanvas;
2661 if (cv == null) {
2662 mThumbnailCanvas = cv = new Canvas();
2663 }
2664
2665 cv.setBitmap(thumbnail);
2666 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2667 mAvailThumbnailBitmap = thumbnail;
2668 thumbnail = null;
2669 }
Dianne Hackborn6311d0a2011-08-02 16:37:58 -07002670 cv.setBitmap(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 } catch (Exception e) {
2674 if (!mInstrumentation.onException(r.activity, e)) {
2675 throw new RuntimeException(
2676 "Unable to create thumbnail of "
2677 + r.intent.getComponent().toShortString()
2678 + ": " + e.toString(), e);
2679 }
2680 thumbnail = null;
2681 }
2682
2683 return thumbnail;
2684 }
2685
Romain Guy65b345f2011-07-27 18:51:50 -07002686 private void handlePauseActivity(IBinder token, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002688 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002690 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 if (userLeaving) {
2692 performUserLeavingActivity(r);
2693 }
Bob Leee5408332009-09-04 18:31:17 -07002694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002696 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002698 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002699 if (r.isPreHoneycomb()) {
2700 QueuedWork.waitToFinish();
2701 }
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 // Tell the activity manager we have paused.
2704 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002705 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 } catch (RemoteException ex) {
2707 }
2708 }
2709 }
2710
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002711 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 mInstrumentation.callActivityOnUserLeaving(r.activity);
2713 }
2714
2715 final Bundle performPauseActivity(IBinder token, boolean finished,
2716 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002717 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 return r != null ? performPauseActivity(r, finished, saveState) : null;
2719 }
2720
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002721 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 boolean saveState) {
2723 if (r.paused) {
2724 if (r.activity.mFinished) {
2725 // If we are finishing, we won't call onResume() in certain cases.
2726 // So here we likewise don't want to call onPause() if the activity
2727 // isn't resumed.
2728 return null;
2729 }
2730 RuntimeException e = new RuntimeException(
2731 "Performing pause of activity that is not resumed: "
2732 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002733 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 }
2735 Bundle state = null;
2736 if (finished) {
2737 r.activity.mFinished = true;
2738 }
2739 try {
2740 // Next have the activity save its current state and managed dialogs...
2741 if (!r.activity.mFinished && saveState) {
2742 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002743 state.setAllowFds(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2745 r.state = state;
2746 }
2747 // Now we are idle.
2748 r.activity.mCalled = false;
2749 mInstrumentation.callActivityOnPause(r.activity);
2750 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2751 if (!r.activity.mCalled) {
2752 throw new SuperNotCalledException(
2753 "Activity " + r.intent.getComponent().toShortString() +
2754 " did not call through to super.onPause()");
2755 }
2756
2757 } catch (SuperNotCalledException e) {
2758 throw e;
2759
2760 } catch (Exception e) {
2761 if (!mInstrumentation.onException(r.activity, e)) {
2762 throw new RuntimeException(
2763 "Unable to pause activity "
2764 + r.intent.getComponent().toShortString()
2765 + ": " + e.toString(), e);
2766 }
2767 }
2768 r.paused = true;
Jeff Hamilton52d32032011-01-08 15:31:26 -06002769
2770 // Notify any outstanding on paused listeners
2771 ArrayList<OnActivityPausedListener> listeners;
2772 synchronized (mOnPauseListeners) {
2773 listeners = mOnPauseListeners.remove(r.activity);
2774 }
2775 int size = (listeners != null ? listeners.size() : 0);
2776 for (int i = 0; i < size; i++) {
2777 listeners.get(i).onPaused(r.activity);
2778 }
2779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 return state;
2781 }
2782
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002783 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002784 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002785 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 }
2787
2788 private static class StopInfo {
2789 Bitmap thumbnail;
2790 CharSequence description;
2791 }
2792
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002793 private static final class ProviderRefCount {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 public int count;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 ProviderRefCount(int pCount) {
2797 count = pCount;
2798 }
2799 }
2800
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002801 /**
2802 * Core implementation of stopping an activity. Note this is a little
2803 * tricky because the server's meaning of stop is slightly different
2804 * than our client -- for the server, stop means to save state and give
2805 * it the result when it is done, but the window may still be visible.
2806 * For the client, we want to call onStop()/onStart() to indicate when
2807 * the activity's UI visibillity changes.
2808 */
Romain Guy65b345f2011-07-27 18:51:50 -07002809 private void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002810 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002811 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002812 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 if (r != null) {
2814 if (!keepShown && r.stopped) {
2815 if (r.activity.mFinished) {
2816 // If we are finishing, we won't call onResume() in certain
2817 // cases. So here we likewise don't want to call onStop()
2818 // if the activity isn't resumed.
2819 return;
2820 }
2821 RuntimeException e = new RuntimeException(
2822 "Performing stop of activity that is not resumed: "
2823 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002824 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 }
2826
2827 if (info != null) {
2828 try {
2829 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07002830 // For now, don't create the thumbnail here; we are
2831 // doing that by doing a screen snapshot.
2832 info.thumbnail = null; //createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 info.description = r.activity.onCreateDescription();
2834 } catch (Exception e) {
2835 if (!mInstrumentation.onException(r.activity, e)) {
2836 throw new RuntimeException(
2837 "Unable to save state of activity "
2838 + r.intent.getComponent().toShortString()
2839 + ": " + e.toString(), e);
2840 }
2841 }
2842 }
2843
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002844 // Next have the activity save its current state and managed dialogs...
2845 if (!r.activity.mFinished && saveState) {
2846 if (r.state == null) {
2847 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002848 state.setAllowFds(false);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002849 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2850 r.state = state;
2851 } else {
2852 state = r.state;
2853 }
2854 }
2855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 if (!keepShown) {
2857 try {
2858 // Now we are idle.
2859 r.activity.performStop();
2860 } catch (Exception e) {
2861 if (!mInstrumentation.onException(r.activity, e)) {
2862 throw new RuntimeException(
2863 "Unable to stop activity "
2864 + r.intent.getComponent().toShortString()
2865 + ": " + e.toString(), e);
2866 }
2867 }
2868 r.stopped = true;
2869 }
2870
2871 r.paused = true;
2872 }
2873 }
2874
Romain Guy65b345f2011-07-27 18:51:50 -07002875 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 View v = r.activity.mDecor;
2877 if (v != null) {
2878 if (show) {
2879 if (!r.activity.mVisibleFromServer) {
2880 r.activity.mVisibleFromServer = true;
2881 mNumVisibleActivities++;
2882 if (r.activity.mVisibleFromClient) {
2883 r.activity.makeVisible();
2884 }
2885 }
2886 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002887 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002888 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 performConfigurationChanged(r.activity, r.newConfig);
2890 r.newConfig = null;
2891 }
2892 } else {
2893 if (r.activity.mVisibleFromServer) {
2894 r.activity.mVisibleFromServer = false;
2895 mNumVisibleActivities--;
2896 v.setVisibility(View.INVISIBLE);
2897 }
2898 }
2899 }
2900 }
2901
Romain Guy65b345f2011-07-27 18:51:50 -07002902 private void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002903 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 r.activity.mConfigChangeFlags |= configChanges;
2905
2906 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002907 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002909 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 TAG, "Finishing stop of " + r + ": show=" + show
2911 + " win=" + r.window);
2912
2913 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002914
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002915 // Make sure any pending writes are now committed.
2916 if (!r.isPreHoneycomb()) {
2917 QueuedWork.waitToFinish();
2918 }
2919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 // Tell activity manager we have been stopped.
2921 try {
2922 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002923 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 } catch (RemoteException ex) {
2925 }
2926 }
2927
2928 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002929 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 if (r.stopped) {
2931 r.activity.performRestart();
2932 r.stopped = false;
2933 }
2934 }
2935
Romain Guy65b345f2011-07-27 18:51:50 -07002936 private void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002937 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002938
2939 if (r == null) {
2940 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2941 return;
2942 }
2943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002945 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 } else if (show && r.stopped) {
2947 // If we are getting ready to gc after going to the background, well
2948 // we are back active so skip it.
2949 unscheduleGcIdler();
2950
2951 r.activity.performRestart();
2952 r.stopped = false;
2953 }
2954 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07002955 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 TAG, "Handle window " + r + " visibility: " + show);
2957 updateVisibility(r, show);
2958 }
2959 }
2960
Romain Guy65b345f2011-07-27 18:51:50 -07002961 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002962 ActivityClientRecord r = mActivities.get(token);
2963
2964 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002965 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002966 return;
2967 }
2968
2969 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002970 if (!r.stopped && !r.isPreHoneycomb()) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002971 try {
2972 // Now we are idle.
2973 r.activity.performStop();
2974 } catch (Exception e) {
2975 if (!mInstrumentation.onException(r.activity, e)) {
2976 throw new RuntimeException(
2977 "Unable to stop activity "
2978 + r.intent.getComponent().toShortString()
2979 + ": " + e.toString(), e);
2980 }
2981 }
2982 r.stopped = true;
2983 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002984
2985 // Make sure any pending writes are now committed.
2986 if (!r.isPreHoneycomb()) {
2987 QueuedWork.waitToFinish();
2988 }
2989
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002990 // Tell activity manager we slept.
2991 try {
2992 ActivityManagerNative.getDefault().activitySlept(r.token);
2993 } catch (RemoteException ex) {
2994 }
2995 } else {
2996 if (r.stopped && r.activity.mVisibleFromServer) {
2997 r.activity.performRestart();
2998 r.stopped = false;
2999 }
3000 }
3001 }
3002
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003003 private void handleSetCoreSettings(Bundle coreSettings) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08003004 synchronized (mPackages) {
3005 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003006 }
3007 }
3008
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003009 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
3010 LoadedApk apk = peekPackageInfo(data.pkg, false);
3011 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003012 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003013 }
3014 apk = peekPackageInfo(data.pkg, true);
3015 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003016 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003017 }
3018 handleConfigurationChanged(mConfiguration, data.info);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003019 WindowManagerImpl.getDefault().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003020 }
3021
Romain Guy65b345f2011-07-27 18:51:50 -07003022 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 final int N = results.size();
3024 for (int i=0; i<N; i++) {
3025 ResultInfo ri = results.get(i);
3026 try {
3027 if (ri.mData != null) {
3028 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3029 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003030 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07003031 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 r.activity.dispatchActivityResult(ri.mResultWho,
3033 ri.mRequestCode, ri.mResultCode, ri.mData);
3034 } catch (Exception e) {
3035 if (!mInstrumentation.onException(r.activity, e)) {
3036 throw new RuntimeException(
3037 "Failure delivering result " + ri + " to activity "
3038 + r.intent.getComponent().toShortString()
3039 + ": " + e.toString(), e);
3040 }
3041 }
3042 }
3043 }
3044
Romain Guy65b345f2011-07-27 18:51:50 -07003045 private void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003046 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003047 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 if (r != null) {
3049 final boolean resumed = !r.paused;
3050 if (!r.activity.mFinished && r.activity.mDecor != null
3051 && r.hideForNow && resumed) {
3052 // We had hidden the activity because it started another
3053 // one... we have gotten a result back and we are not
3054 // paused, so make sure our window is visible.
3055 updateVisibility(r, true);
3056 }
3057 if (resumed) {
3058 try {
3059 // Now we are idle.
3060 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003061 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 mInstrumentation.callActivityOnPause(r.activity);
3063 if (!r.activity.mCalled) {
3064 throw new SuperNotCalledException(
3065 "Activity " + r.intent.getComponent().toShortString()
3066 + " did not call through to super.onPause()");
3067 }
3068 } catch (SuperNotCalledException e) {
3069 throw e;
3070 } catch (Exception e) {
3071 if (!mInstrumentation.onException(r.activity, e)) {
3072 throw new RuntimeException(
3073 "Unable to pause activity "
3074 + r.intent.getComponent().toShortString()
3075 + ": " + e.toString(), e);
3076 }
3077 }
3078 }
3079 deliverResults(r, res.results);
3080 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07003081 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003082 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 }
3084 }
3085 }
3086
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003087 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 return performDestroyActivity(token, finishing, 0, false);
3089 }
3090
Romain Guy65b345f2011-07-27 18:51:50 -07003091 private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003093 ActivityClientRecord r = mActivities.get(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003094 Class activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003095 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003097 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 r.activity.mConfigChangeFlags |= configChanges;
3099 if (finishing) {
3100 r.activity.mFinished = true;
3101 }
3102 if (!r.paused) {
3103 try {
3104 r.activity.mCalled = false;
3105 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003106 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 r.activity.getComponentName().getClassName());
3108 if (!r.activity.mCalled) {
3109 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003110 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 + " did not call through to super.onPause()");
3112 }
3113 } catch (SuperNotCalledException e) {
3114 throw e;
3115 } catch (Exception e) {
3116 if (!mInstrumentation.onException(r.activity, e)) {
3117 throw new RuntimeException(
3118 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003119 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 + ": " + e.toString(), e);
3121 }
3122 }
3123 r.paused = true;
3124 }
3125 if (!r.stopped) {
3126 try {
3127 r.activity.performStop();
3128 } catch (SuperNotCalledException e) {
3129 throw e;
3130 } catch (Exception e) {
3131 if (!mInstrumentation.onException(r.activity, e)) {
3132 throw new RuntimeException(
3133 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003134 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 + ": " + e.toString(), e);
3136 }
3137 }
3138 r.stopped = true;
3139 }
3140 if (getNonConfigInstance) {
3141 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003142 r.lastNonConfigurationInstances
3143 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 } catch (Exception e) {
3145 if (!mInstrumentation.onException(r.activity, e)) {
3146 throw new RuntimeException(
3147 "Unable to retain activity "
3148 + r.intent.getComponent().toShortString()
3149 + ": " + e.toString(), e);
3150 }
3151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 }
3153 try {
3154 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07003155 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 if (!r.activity.mCalled) {
3157 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003158 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 " did not call through to super.onDestroy()");
3160 }
3161 if (r.window != null) {
3162 r.window.closeAllPanels();
3163 }
3164 } catch (SuperNotCalledException e) {
3165 throw e;
3166 } catch (Exception e) {
3167 if (!mInstrumentation.onException(r.activity, e)) {
3168 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003169 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3170 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 }
3172 }
3173 }
3174 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003175 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 return r;
3177 }
3178
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003179 private static String safeToComponentShortString(Intent intent) {
3180 ComponentName component = intent.getComponent();
3181 return component == null ? "[Unknown]" : component.toShortString();
3182 }
3183
Romain Guy65b345f2011-07-27 18:51:50 -07003184 private void handleDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003186 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 configChanges, getNonConfigInstance);
3188 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003189 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 WindowManager wm = r.activity.getWindowManager();
3191 View v = r.activity.mDecor;
3192 if (v != null) {
3193 if (r.activity.mVisibleFromServer) {
3194 mNumVisibleActivities--;
3195 }
3196 IBinder wtoken = v.getWindowToken();
3197 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003198 if (r.onlyLocalRequest) {
3199 // Hold off on removing this until the new activity's
3200 // window is being added.
3201 r.mPendingRemoveWindow = v;
3202 r.mPendingRemoveWindowManager = wm;
3203 } else {
3204 wm.removeViewImmediate(v);
3205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003207 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 WindowManagerImpl.getDefault().closeAll(wtoken,
3209 r.activity.getClass().getName(), "Activity");
3210 }
3211 r.activity.mDecor = null;
3212 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003213 if (r.mPendingRemoveWindow == null) {
3214 // If we are delaying the removal of the activity window, then
3215 // we can't clean up all windows here. Note that we can't do
3216 // so later either, which means any windows that aren't closed
3217 // by the app will leak. Well we try to warning them a lot
3218 // about leaking windows, because that is a bug, so if they are
3219 // using this recreate facility then they get to live with leaks.
3220 WindowManagerImpl.getDefault().closeAll(token,
3221 r.activity.getClass().getName(), "Activity");
3222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223
3224 // Mocked out contexts won't be participating in the normal
3225 // process lifecycle, but if we're running with a proper
3226 // ApplicationContext we need to have it tear down things
3227 // cleanly.
3228 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003229 if (c instanceof ContextImpl) {
3230 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 r.activity.getClass().getName(), "Activity");
3232 }
3233 }
3234 if (finishing) {
3235 try {
3236 ActivityManagerNative.getDefault().activityDestroyed(token);
3237 } catch (RemoteException ex) {
3238 // If the system process has died, it's game over for everyone.
3239 }
3240 }
3241 }
3242
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003243 public final void requestRelaunchActivity(IBinder token,
3244 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
3245 int configChanges, boolean notResumed, Configuration config,
3246 boolean fromServer) {
3247 ActivityClientRecord target = null;
3248
3249 synchronized (mPackages) {
3250 for (int i=0; i<mRelaunchingActivities.size(); i++) {
3251 ActivityClientRecord r = mRelaunchingActivities.get(i);
3252 if (r.token == token) {
3253 target = r;
3254 if (pendingResults != null) {
3255 if (r.pendingResults != null) {
3256 r.pendingResults.addAll(pendingResults);
3257 } else {
3258 r.pendingResults = pendingResults;
3259 }
3260 }
3261 if (pendingNewIntents != null) {
3262 if (r.pendingIntents != null) {
3263 r.pendingIntents.addAll(pendingNewIntents);
3264 } else {
3265 r.pendingIntents = pendingNewIntents;
3266 }
3267 }
3268 break;
3269 }
3270 }
3271
3272 if (target == null) {
3273 target = new ActivityClientRecord();
3274 target.token = token;
3275 target.pendingResults = pendingResults;
3276 target.pendingIntents = pendingNewIntents;
3277 if (!fromServer) {
3278 ActivityClientRecord existing = mActivities.get(token);
3279 if (existing != null) {
3280 target.startsNotResumed = existing.paused;
3281 }
3282 target.onlyLocalRequest = true;
3283 }
3284 mRelaunchingActivities.add(target);
3285 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
3286 }
3287
3288 if (fromServer) {
3289 target.startsNotResumed = notResumed;
3290 target.onlyLocalRequest = false;
3291 }
3292 if (config != null) {
3293 target.createdConfig = config;
3294 }
3295 target.pendingConfigChanges |= configChanges;
3296 }
3297 }
3298
Romain Guy65b345f2011-07-27 18:51:50 -07003299 private void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 // If we are getting ready to gc after going to the background, well
3301 // we are back active so skip it.
3302 unscheduleGcIdler();
3303
3304 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003305 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07003306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 // First: make sure we have the most recent configuration and most
3308 // recent version of the activity, or skip it if some previous call
3309 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003310 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 int N = mRelaunchingActivities.size();
3312 IBinder token = tmp.token;
3313 tmp = null;
3314 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003315 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 if (r.token == token) {
3317 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003318 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 mRelaunchingActivities.remove(i);
3320 i--;
3321 N--;
3322 }
3323 }
Bob Leee5408332009-09-04 18:31:17 -07003324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003326 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 return;
3328 }
Bob Leee5408332009-09-04 18:31:17 -07003329
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003330 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
3331 + tmp.token + " with configChanges=0x"
3332 + Integer.toHexString(configChanges));
3333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 if (mPendingConfiguration != null) {
3335 changedConfig = mPendingConfiguration;
3336 mPendingConfiguration = null;
3337 }
3338 }
Bob Leee5408332009-09-04 18:31:17 -07003339
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003340 if (tmp.createdConfig != null) {
3341 // If the activity manager is passing us its current config,
3342 // assume that is really what we want regardless of what we
3343 // may have pending.
3344 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003345 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
3346 && mConfiguration.diff(tmp.createdConfig) != 0)) {
3347 if (changedConfig == null
3348 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
3349 changedConfig = tmp.createdConfig;
3350 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003351 }
3352 }
3353
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003354 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003355 + tmp.token + ": changedConfig=" + changedConfig);
3356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 // If there was a pending configuration change, execute it first.
3358 if (changedConfig != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003359 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 }
Bob Leee5408332009-09-04 18:31:17 -07003361
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003362 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003363 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 if (r == null) {
3365 return;
3366 }
Bob Leee5408332009-09-04 18:31:17 -07003367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003369 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003370 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003371
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003372 r.activity.mChangingConfigurations = true;
3373
Dianne Hackborne2b04802010-12-09 09:24:55 -08003374 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08003376 performPauseActivity(r.token, false, r.isPreHoneycomb());
3377 }
3378 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
3379 r.state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04003380 r.state.setAllowFds(false);
Dianne Hackborne2b04802010-12-09 09:24:55 -08003381 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 }
Bob Leee5408332009-09-04 18:31:17 -07003383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 r.activity = null;
3387 r.window = null;
3388 r.hideForNow = false;
3389 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003390 // Merge any pending results and pending intents; don't just replace them
3391 if (tmp.pendingResults != null) {
3392 if (r.pendingResults == null) {
3393 r.pendingResults = tmp.pendingResults;
3394 } else {
3395 r.pendingResults.addAll(tmp.pendingResults);
3396 }
3397 }
3398 if (tmp.pendingIntents != null) {
3399 if (r.pendingIntents == null) {
3400 r.pendingIntents = tmp.pendingIntents;
3401 } else {
3402 r.pendingIntents.addAll(tmp.pendingIntents);
3403 }
3404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07003406
Christopher Tateb70f3df2009-04-07 16:07:59 -07003407 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 }
3409
Romain Guy65b345f2011-07-27 18:51:50 -07003410 private void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003411 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 Bitmap thumbnail = createThumbnailBitmap(r);
3413 CharSequence description = null;
3414 try {
3415 description = r.activity.onCreateDescription();
3416 } catch (Exception e) {
3417 if (!mInstrumentation.onException(r.activity, e)) {
3418 throw new RuntimeException(
3419 "Unable to create description of activity "
3420 + r.intent.getComponent().toShortString()
3421 + ": " + e.toString(), e);
3422 }
3423 }
3424 //System.out.println("Reporting top thumbnail " + thumbnail);
3425 try {
3426 ActivityManagerNative.getDefault().reportThumbnail(
3427 token, thumbnail, description);
3428 } catch (RemoteException ex) {
3429 }
3430 }
3431
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003432 ArrayList<ComponentCallbacks2> collectComponentCallbacksLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003434 ArrayList<ComponentCallbacks2> callbacks
3435 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07003436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003438 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003440 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 Activity a = ar.activity;
3442 if (a != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003443 Configuration thisConfig = applyConfigCompatMainThread(newConfig,
3444 ar.packageInfo.mCompatibilityInfo.getIfNeeded());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 if (!ar.activity.mFinished && (allActivities ||
3446 (a != null && !ar.paused))) {
3447 // If the activity is currently resumed, its configuration
3448 // needs to change right now.
3449 callbacks.add(a);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003450 } else if (thisConfig != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 // Otherwise, we will tell it about the change
3452 // the next time it is resumed or shown. Note that
3453 // the activity manager may, before then, decide the
3454 // activity needs to be destroyed to handle its new
3455 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003456 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003457 + ar.activityInfo.name + " newConfig=" + thisConfig);
3458 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 }
3460 }
3461 }
3462 }
3463 if (mServices.size() > 0) {
3464 Iterator<Service> it = mServices.values().iterator();
3465 while (it.hasNext()) {
3466 callbacks.add(it.next());
3467 }
3468 }
3469 synchronized (mProviderMap) {
3470 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003471 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 while (it.hasNext()) {
3473 callbacks.add(it.next().mLocalProvider);
3474 }
3475 }
3476 }
3477 final int N = mAllApplications.size();
3478 for (int i=0; i<N; i++) {
3479 callbacks.add(mAllApplications.get(i));
3480 }
Bob Leee5408332009-09-04 18:31:17 -07003481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 return callbacks;
3483 }
Bob Leee5408332009-09-04 18:31:17 -07003484
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003485 private final void performConfigurationChanged(
3486 ComponentCallbacks2 cb, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 // Only for Activity objects, check that they actually call up to their
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003488 // superclass implementation. ComponentCallbacks2 is an interface, so
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 // we check the runtime type and act accordingly.
3490 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3491 if (activity != null) {
3492 activity.mCalled = false;
3493 }
Bob Leee5408332009-09-04 18:31:17 -07003494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 boolean shouldChangeConfig = false;
3496 if ((activity == null) || (activity.mCurrentConfig == null)) {
3497 shouldChangeConfig = true;
3498 } else {
Bob Leee5408332009-09-04 18:31:17 -07003499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 // If the new config is the same as the config this Activity
3501 // is already running with then don't bother calling
3502 // onConfigurationChanged
3503 int diff = activity.mCurrentConfig.diff(config);
3504 if (diff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 // If this activity doesn't handle any of the config changes
3506 // then don't bother calling onConfigurationChanged as we're
3507 // going to destroy it.
Dianne Hackborne6676352011-06-01 16:51:20 -07003508 if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 shouldChangeConfig = true;
3510 }
3511 }
3512 }
Bob Leee5408332009-09-04 18:31:17 -07003513
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003514 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003515 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 if (shouldChangeConfig) {
3517 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 if (activity != null) {
3520 if (!activity.mCalled) {
3521 throw new SuperNotCalledException(
3522 "Activity " + activity.getLocalClassName() +
3523 " did not call through to super.onConfigurationChanged()");
3524 }
3525 activity.mConfigChangeFlags = 0;
3526 activity.mCurrentConfig = new Configuration(config);
3527 }
3528 }
3529 }
3530
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003531 public final void applyConfigurationToResources(Configuration config) {
3532 synchronized (mPackages) {
3533 applyConfigurationToResourcesLocked(config, null);
3534 }
3535 }
3536
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003537 final boolean applyConfigurationToResourcesLocked(Configuration config,
3538 CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003539 if (mResConfiguration == null) {
3540 mResConfiguration = new Configuration();
3541 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003542 if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003543 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003544 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003545 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003546 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003547 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003548 DisplayMetrics dm = getDisplayMetricsLocked(null, true);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003549
3550 if (compat != null && (mResCompatibilityInfo == null ||
3551 !mResCompatibilityInfo.equals(compat))) {
3552 mResCompatibilityInfo = compat;
3553 changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT
3554 | ActivityInfo.CONFIG_SCREEN_SIZE
3555 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3556 }
Bob Leee5408332009-09-04 18:31:17 -07003557
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003558 // set it for java, this also affects newly created Resources
3559 if (config.locale != null) {
3560 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 }
Bob Leee5408332009-09-04 18:31:17 -07003562
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003563 Resources.updateSystemConfiguration(config, dm, compat);
Bob Leee5408332009-09-04 18:31:17 -07003564
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003565 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003566 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003567
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003568 Iterator<WeakReference<Resources>> it =
3569 mActiveResources.values().iterator();
3570 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3571 // mActiveResources.entrySet().iterator();
3572 while (it.hasNext()) {
3573 WeakReference<Resources> v = it.next();
3574 Resources r = v.get();
3575 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003576 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003577 + r + " config to: " + config);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003578 r.updateConfiguration(config, dm, compat);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003579 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003580 // + " " + r + ": " + r.getConfiguration());
3581 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003582 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003583 it.remove();
3584 }
3585 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003586
3587 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003588 }
Dianne Hackborn836e2622011-10-04 18:32:39 -07003589
3590 final Configuration applyCompatConfiguration() {
3591 Configuration config = mConfiguration;
3592 if (mCompatConfiguration == null) {
3593 mCompatConfiguration = new Configuration();
3594 }
3595 mCompatConfiguration.setTo(mConfiguration);
3596 if (mResCompatibilityInfo != null && !mResCompatibilityInfo.supportsScreen()) {
3597 mResCompatibilityInfo.applyToConfiguration(mCompatConfiguration);
3598 config = mCompatConfiguration;
3599 }
3600 return config;
3601 }
3602
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003603 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003604
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003605 ArrayList<ComponentCallbacks2> callbacks = null;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003606
3607 synchronized (mPackages) {
3608 if (mPendingConfiguration != null) {
3609 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3610 config = mPendingConfiguration;
3611 }
3612 mPendingConfiguration = null;
3613 }
3614
3615 if (config == null) {
3616 return;
3617 }
3618
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003619 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003620 + config);
3621
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003622 applyConfigurationToResourcesLocked(config, compat);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 if (mConfiguration == null) {
3625 mConfiguration = new Configuration();
3626 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003627 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003628 return;
3629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 mConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003631 config = applyCompatConfiguration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 callbacks = collectComponentCallbacksLocked(false, config);
3633 }
Romain Guy65b345f2011-07-27 18:51:50 -07003634
3635 // Cleanup hardware accelerated stuff
3636 WindowManagerImpl.getDefault().trimLocalMemory();
Bob Leee5408332009-09-04 18:31:17 -07003637
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003638 if (callbacks != null) {
3639 final int N = callbacks.size();
3640 for (int i=0; i<N; i++) {
3641 performConfigurationChanged(callbacks.get(i), config);
3642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 }
3644 }
3645
3646 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003647 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 if (r == null || r.activity == null) {
3649 return;
3650 }
Bob Leee5408332009-09-04 18:31:17 -07003651
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003652 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003653 + r.activityInfo.name);
3654
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003655 performConfigurationChanged(r.activity, mCompatConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 }
3657
Romain Guy7eabe552011-07-21 14:56:34 -07003658 final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003659 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003660 try {
Romain Guy7eabe552011-07-21 14:56:34 -07003661 switch (profileType) {
3662 case 1:
3663 ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor());
3664 break;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003665 default:
3666 mProfiler.setProfiler(pcd.path, pcd.fd);
3667 mProfiler.autoStopProfiler = false;
3668 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003669 break;
3670 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003671 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003672 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003673 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003674 } finally {
3675 try {
3676 pcd.fd.close();
3677 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003678 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003679 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003680 }
3681 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07003682 switch (profileType) {
3683 case 1:
3684 ViewDebug.stopLooperProfiling();
3685 break;
3686 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003687 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003688 break;
Romain Guy7eabe552011-07-21 14:56:34 -07003689 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003690 }
3691 }
Bob Leee5408332009-09-04 18:31:17 -07003692
Andy McFadden824c5102010-07-09 16:26:57 -07003693 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3694 if (managed) {
3695 try {
3696 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3697 } catch (IOException e) {
3698 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3699 + " -- can the process access this path?");
3700 } finally {
3701 try {
3702 dhd.fd.close();
3703 } catch (IOException e) {
3704 Slog.w(TAG, "Failure closing profile fd", e);
3705 }
3706 }
3707 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003708 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003709 }
3710 }
3711
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003712 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3713 boolean hasPkgInfo = false;
3714 if (packages != null) {
3715 for (int i=packages.length-1; i>=0; i--) {
3716 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3717 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003718 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003719 ref = mPackages.get(packages[i]);
3720 if (ref != null && ref.get() != null) {
3721 hasPkgInfo = true;
3722 } else {
3723 ref = mResourcePackages.get(packages[i]);
3724 if (ref != null && ref.get() != null) {
3725 hasPkgInfo = true;
3726 }
3727 }
3728 }
3729 mPackages.remove(packages[i]);
3730 mResourcePackages.remove(packages[i]);
3731 }
3732 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003733 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003734 hasPkgInfo);
3735 }
3736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 final void handleLowMemory() {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003738 ArrayList<ComponentCallbacks2> callbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003740 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 callbacks = collectComponentCallbacksLocked(true, null);
3742 }
Bob Leee5408332009-09-04 18:31:17 -07003743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 final int N = callbacks.size();
3745 for (int i=0; i<N; i++) {
3746 callbacks.get(i).onLowMemory();
3747 }
3748
Chris Tatece229052009-03-25 16:44:52 -07003749 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3750 if (Process.myUid() != Process.SYSTEM_UID) {
3751 int sqliteReleased = SQLiteDatabase.releaseMemory();
3752 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3753 }
Bob Leee5408332009-09-04 18:31:17 -07003754
Mike Reedcaf0df12009-04-27 14:32:05 -04003755 // Ask graphics to free up as much as possible (font/image caches)
3756 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757
3758 BinderInternal.forceGc("mem");
3759 }
3760
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003761 final void handleTrimMemory(int level) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003762 ArrayList<ComponentCallbacks2> callbacks;
3763
3764 synchronized (mPackages) {
3765 callbacks = collectComponentCallbacksLocked(true, null);
3766 }
3767
3768 final int N = callbacks.size();
3769 for (int i=0; i<N; i++) {
3770 callbacks.get(i).onTrimMemory(level);
3771 }
Teng-Hui Zhua34eb912012-01-25 13:46:16 -08003772 WindowManagerImpl.getDefault().trimMemory(level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003773 }
3774
Romain Guya9582652011-11-10 14:20:10 -08003775 private void setupGraphicsSupport(LoadedApk info) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003776 if (Process.isIsolated()) {
3777 // Isolated processes aren't going to do UI.
3778 return;
3779 }
Romain Guya9582652011-11-10 14:20:10 -08003780 try {
3781 int uid = Process.myUid();
3782 String[] packages = getPackageManager().getPackagesForUid(uid);
3783
3784 // If there are several packages in this application we won't
3785 // initialize the graphics disk caches
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003786 if (packages != null && packages.length == 1) {
Romain Guya9582652011-11-10 14:20:10 -08003787 ContextImpl appContext = new ContextImpl();
3788 appContext.init(info, null, this);
3789
3790 HardwareRenderer.setupDiskCache(appContext.getCacheDir());
Jason Samsa6f338c2012-02-24 16:22:16 -08003791 RenderScript.setupDiskCache(appContext.getCacheDir());
Romain Guya9582652011-11-10 14:20:10 -08003792 }
3793 } catch (RemoteException e) {
3794 // Ignore
3795 }
3796 }
3797
Romain Guy65b345f2011-07-27 18:51:50 -07003798 private void handleBindApplication(AppBindData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 mBoundApplication = data;
3800 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003801 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003803 mProfiler = new Profiler();
3804 mProfiler.profileFile = data.initProfileFile;
3805 mProfiler.profileFd = data.initProfileFd;
3806 mProfiler.autoStopProfiler = data.initAutoStopProfiler;
3807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003809 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 android.ddm.DdmHandleAppName.setAppName(data.processName);
3811
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003812 if (data.persistent) {
3813 // Persistent processes on low-memory devices do not get to
3814 // use hardware accelerated drawing, since this can add too much
3815 // overhead to the process.
3816 Display display = WindowManagerImpl.getDefault().getDefaultDisplay();
3817 if (!ActivityManager.isHighEndGfx(display)) {
3818 HardwareRenderer.disable(false);
3819 }
3820 }
Romain Guya9582652011-11-10 14:20:10 -08003821
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003822 if (mProfiler.profileFd != null) {
3823 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003824 }
3825
Joe Onoratod630f102011-03-17 18:42:26 -07003826 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
3827 // implementation to use the pool executor. Normally, we use the
3828 // serialized executor as the default. This has to happen in the
3829 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07003830 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07003831 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
3832 }
3833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 /*
3835 * Before spawning a new process, reset the time zone to be the system time zone.
3836 * This needs to be done because the system time zone could have changed after the
3837 * the spawning of this process. Without doing this this process would have the incorrect
3838 * system time zone.
3839 */
3840 TimeZone.setDefault(null);
3841
3842 /*
3843 * Initialize the default locale in this process for the reasons we set the time zone.
3844 */
3845 Locale.setDefault(data.config.locale);
3846
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003847 /*
3848 * Update the system configuration since its preloaded and might not
3849 * reflect configuration changes. The configuration object passed
3850 * in AppBindData can be safely assumed to be up to date
3851 */
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003852 applyConfigurationToResourcesLocked(data.config, data.compatInfo);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003853 applyCompatConfiguration();
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003854
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003855 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856
Romain Guya9582652011-11-10 14:20:10 -08003857 setupGraphicsSupport(data.info);
3858
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003859 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003860 * For system applications on userdebug/eng builds, log stack
3861 * traces of disk and network access to dropbox for analysis.
3862 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003863 if ((data.appInfo.flags &
3864 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003865 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3866 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003867 }
3868
3869 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003870 * For apps targetting SDK Honeycomb or later, we don't allow
3871 * network usage on the main event loop / UI thread.
3872 *
3873 * Note to those grepping: this is what ultimately throws
3874 * NetworkOnMainThreadException ...
3875 */
3876 if (data.appInfo.targetSdkVersion > 9) {
3877 StrictMode.enableDeathOnNetwork();
3878 }
3879
3880 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003881 * Switch this process to density compatibility mode if needed.
3882 */
3883 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3884 == 0) {
3885 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3886 }
Bob Leee5408332009-09-04 18:31:17 -07003887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3889 // XXX should have option to change the port.
3890 Debug.changeDebugPort(8100);
3891 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003892 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 + " is waiting for the debugger on port 8100...");
3894
3895 IActivityManager mgr = ActivityManagerNative.getDefault();
3896 try {
3897 mgr.showWaitingForDebugger(mAppThread, true);
3898 } catch (RemoteException ex) {
3899 }
3900
3901 Debug.waitForDebugger();
3902
3903 try {
3904 mgr.showWaitingForDebugger(mAppThread, false);
3905 } catch (RemoteException ex) {
3906 }
3907
3908 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003909 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 + " can be debugged on port 8100...");
3911 }
3912 }
3913
Robert Greenwalt434203a2010-10-11 16:00:27 -07003914 /**
3915 * Initialize the default http proxy in this process for the reasons we set the time zone.
3916 */
3917 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08003918 if (b != null) {
3919 // In pre-boot mode (doing initial launch to collect password), not
3920 // all system is up. This includes the connectivity service, so don't
3921 // crash if we can't get it.
3922 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3923 try {
3924 ProxyProperties proxyProperties = service.getProxy();
3925 Proxy.setHttpProxySystemProperty(proxyProperties);
3926 } catch (RemoteException e) {}
3927 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003930 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 appContext.init(data.info, null, this);
3932 InstrumentationInfo ii = null;
3933 try {
3934 ii = appContext.getPackageManager().
3935 getInstrumentationInfo(data.instrumentationName, 0);
3936 } catch (PackageManager.NameNotFoundException e) {
3937 }
3938 if (ii == null) {
3939 throw new RuntimeException(
3940 "Unable to find instrumentation info for: "
3941 + data.instrumentationName);
3942 }
3943
3944 mInstrumentationAppDir = ii.sourceDir;
3945 mInstrumentationAppPackage = ii.packageName;
3946 mInstrumentedAppDir = data.info.getAppDir();
3947
3948 ApplicationInfo instrApp = new ApplicationInfo();
3949 instrApp.packageName = ii.packageName;
3950 instrApp.sourceDir = ii.sourceDir;
3951 instrApp.publicSourceDir = ii.publicSourceDir;
3952 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003953 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003954 LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003956 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 instrContext.init(pi, null, this);
3958
3959 try {
3960 java.lang.ClassLoader cl = instrContext.getClassLoader();
3961 mInstrumentation = (Instrumentation)
3962 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3963 } catch (Exception e) {
3964 throw new RuntimeException(
3965 "Unable to instantiate instrumentation "
3966 + data.instrumentationName + ": " + e.toString(), e);
3967 }
3968
3969 mInstrumentation.init(this, instrContext, appContext,
3970 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3971
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003972 if (mProfiler.profileFile != null && !ii.handleProfiling
3973 && mProfiler.profileFd == null) {
3974 mProfiler.handlingProfiling = true;
3975 File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 file.getParentFile().mkdirs();
3977 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3978 }
3979
3980 try {
3981 mInstrumentation.onCreate(data.instrumentationArgs);
3982 }
3983 catch (Exception e) {
3984 throw new RuntimeException(
3985 "Exception thrown in onCreate() of "
3986 + data.instrumentationName + ": " + e.toString(), e);
3987 }
3988
3989 } else {
3990 mInstrumentation = new Instrumentation();
3991 }
3992
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003993 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08003994 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003995 }
3996
Jeff Sharkey7c501672012-02-28 12:08:37 -08003997 // allow disk access during application and provider setup. this could
3998 // block processing ordered broadcasts, but later processing would
3999 // probably end up doing the same disk access. restore not guarded with
4000 // finally block, since exceptions here will take down the application.
4001 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
4002
Christopher Tate181fafa2009-05-14 11:12:14 -07004003 // If the app is being launched for full backup or restore, bring it up in
4004 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08004005 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 mInitialApplication = app;
4007
Christopher Tate75a99702011-05-18 16:28:19 -07004008 // don't bring up providers in restricted mode; they may depend on the
4009 // app's custom Application class
Jeff Sharkey7c501672012-02-28 12:08:37 -08004010 if (!data.restrictedBackupMode) {
Christopher Tate75a99702011-05-18 16:28:19 -07004011 List<ProviderInfo> providers = data.providers;
4012 if (providers != null) {
4013 installContentProviders(app, providers);
4014 // For process that contains content providers, we want to
4015 // ensure that the JIT is enabled "at some point".
4016 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
4017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 }
4019
4020 try {
4021 mInstrumentation.callApplicationOnCreate(app);
4022 } catch (Exception e) {
4023 if (!mInstrumentation.onException(app, e)) {
4024 throw new RuntimeException(
4025 "Unable to create application " + app.getClass().getName()
4026 + ": " + e.toString(), e);
4027 }
4028 }
Jeff Sharkey7c501672012-02-28 12:08:37 -08004029
4030 StrictMode.setThreadPolicy(savedPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 }
4032
4033 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
4034 IActivityManager am = ActivityManagerNative.getDefault();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07004035 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
4036 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 Debug.stopMethodTracing();
4038 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004039 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 // + ", app thr: " + mAppThread);
4041 try {
4042 am.finishInstrumentation(mAppThread, resultCode, results);
4043 } catch (RemoteException ex) {
4044 }
4045 }
4046
Romain Guy65b345f2011-07-27 18:51:50 -07004047 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 Context context, List<ProviderInfo> providers) {
4049 final ArrayList<IActivityManager.ContentProviderHolder> results =
4050 new ArrayList<IActivityManager.ContentProviderHolder>();
4051
4052 Iterator<ProviderInfo> i = providers.iterator();
4053 while (i.hasNext()) {
4054 ProviderInfo cpi = i.next();
4055 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07004056 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 buf.append(cpi.authority);
4058 buf.append(": ");
4059 buf.append(cpi.name);
4060 Log.i(TAG, buf.toString());
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004061 IContentProvider cp = installProvider(context, null, cpi,
4062 false /*noisy*/, true /*noReleaseNeeded*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 if (cp != null) {
4064 IActivityManager.ContentProviderHolder cph =
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004065 new IActivityManager.ContentProviderHolder(cpi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 cph.provider = cp;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004067 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 }
4070 }
4071
4072 try {
4073 ActivityManagerNative.getDefault().publishContentProviders(
4074 getApplicationThread(), results);
4075 } catch (RemoteException ex) {
4076 }
4077 }
4078
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004079 public final IContentProvider acquireProvider(Context c, String name) {
4080 IContentProvider provider = acquireExistingProvider(c, name);
4081 if (provider != null) {
4082 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 }
4084
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004085 // There is a possible race here. Another thread may try to acquire
4086 // the same provider at the same time. When this happens, we want to ensure
4087 // that the first one wins.
4088 // Note that we cannot hold the lock while acquiring and installing the
4089 // provider since it might take a long time to run and it could also potentially
4090 // be re-entrant in the case where the provider is in the same process.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 IActivityManager.ContentProviderHolder holder = null;
4092 try {
4093 holder = ActivityManagerNative.getDefault().getContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004094 getApplicationThread(), name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 } catch (RemoteException ex) {
4096 }
4097 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004098 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 return null;
4100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004102 // Install provider will increment the reference count for us, and break
4103 // any ties in the race.
4104 provider = installProvider(c, holder.provider, holder.info,
4105 true /*noisy*/, holder.noReleaseNeeded);
4106 if (holder.provider != null && provider != holder.provider) {
4107 if (localLOGV) {
4108 Slog.v(TAG, "acquireProvider: lost the race, releasing extraneous "
4109 + "reference to the content provider");
4110 }
4111 try {
4112 ActivityManagerNative.getDefault().removeContentProvider(
4113 getApplicationThread(), name);
4114 } catch (RemoteException ex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 }
4116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 return provider;
4118 }
4119
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004120 public final IContentProvider acquireExistingProvider(Context c, String name) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004121 synchronized (mProviderMap) {
4122 ProviderClientRecord pr = mProviderMap.get(name);
4123 if (pr == null) {
4124 return null;
4125 }
4126
4127 IContentProvider provider = pr.mProvider;
4128 IBinder jBinder = provider.asBinder();
4129
4130 // Only increment the ref count if we have one. If we don't then the
4131 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004132 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004133 if (prc != null) {
4134 prc.count += 1;
4135 if (prc.count == 1) {
4136 if (localLOGV) {
4137 Slog.v(TAG, "acquireExistingProvider: "
4138 + "snatched provider from the jaws of death");
4139 }
4140 // Because the provider previously had a reference count of zero,
4141 // it was scheduled to be removed. Cancel that.
4142 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4143 }
4144 }
4145 return provider;
4146 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004147 }
4148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 public final boolean releaseProvider(IContentProvider provider) {
4150 if(provider == null) {
4151 return false;
4152 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004155 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004157 if (prc == null) {
4158 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004160 }
4161
4162 if (prc.count == 0) {
4163 if (localLOGV) Slog.v(TAG, "releaseProvider: ref count already 0, how?");
4164 return false;
4165 }
4166
4167 prc.count -= 1;
4168 if (prc.count == 0) {
4169 // Schedule the actual remove asynchronously, since we don't know the context
4170 // this will be called in.
4171 // TODO: it would be nice to post a delayed message, so
4172 // if we come back and need the same provider quickly
4173 // we will still have it available.
4174 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4175 mH.sendMessage(msg);
4176 }
4177 return true;
4178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 }
4180
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004181 final void completeRemoveProvider(IContentProvider provider) {
4182 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004183 String remoteProviderName = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004184 synchronized(mProviderMap) {
4185 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004186 if (prc == null) {
4187 // Either no release is needed (so we shouldn't be here) or the
4188 // provider was already released.
4189 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: release not needed");
4190 return;
4191 }
4192
4193 if (prc.count != 0) {
4194 // There was a race! Some other client managed to acquire
4195 // the provider before the removal was completed.
4196 // Abort the removal. We will do it later.
4197 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: lost the race, "
4198 + "provider still in use");
4199 return;
4200 }
4201
4202 mProviderRefCountMap.remove(jBinder);
4203
4204 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
4205 while (iter.hasNext()) {
4206 ProviderClientRecord pr = iter.next();
4207 IBinder myBinder = pr.mProvider.asBinder();
4208 if (myBinder == jBinder) {
4209 iter.remove();
4210 if (pr.mLocalProvider == null) {
4211 myBinder.unlinkToDeath(pr, 0);
4212 if (remoteProviderName == null) {
4213 remoteProviderName = pr.mName;
4214 }
4215 }
4216 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004217 }
4218 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004219
4220 if (remoteProviderName != null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004221 try {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004222 if (localLOGV) {
4223 Slog.v(TAG, "removeProvider: Invoking ActivityManagerNative."
4224 + "removeContentProvider(" + remoteProviderName + ")");
4225 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004226 ActivityManagerNative.getDefault().removeContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004227 getApplicationThread(), remoteProviderName);
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004228 } catch (RemoteException e) {
4229 //do nothing content provider object is dead any way
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004230 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004231 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233
4234 final void removeDeadProvider(String name, IContentProvider provider) {
4235 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004236 ProviderClientRecord pr = mProviderMap.get(name);
Jeff Brown2a4c5ac2011-08-23 11:58:26 -07004237 if (pr != null && pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004238 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004239 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004240 if (removed != null) {
4241 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 }
4244 }
4245 }
4246
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004247 /**
4248 * Installs the provider.
4249 *
4250 * Providers that are local to the process or that come from the system server
4251 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
4252 * Other remote providers are reference counted. The initial reference count
4253 * for all reference counted providers is one. Providers that are not reference
4254 * counted do not have a reference count (at all).
4255 *
4256 * This method detects when a provider has already been installed. When this happens,
4257 * it increments the reference count of the existing provider (if appropriate)
4258 * and returns the existing provider. This can happen due to concurrent
4259 * attempts to acquire the same provider.
4260 */
Romain Guy65b345f2011-07-27 18:51:50 -07004261 private IContentProvider installProvider(Context context,
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004262 IContentProvider provider, ProviderInfo info,
4263 boolean noisy, boolean noReleaseNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 ContentProvider localProvider = null;
4265 if (provider == null) {
4266 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004267 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 + info.name);
4269 }
4270 Context c = null;
4271 ApplicationInfo ai = info.applicationInfo;
4272 if (context.getPackageName().equals(ai.packageName)) {
4273 c = context;
4274 } else if (mInitialApplication != null &&
4275 mInitialApplication.getPackageName().equals(ai.packageName)) {
4276 c = mInitialApplication;
4277 } else {
4278 try {
4279 c = context.createPackageContext(ai.packageName,
4280 Context.CONTEXT_INCLUDE_CODE);
4281 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07004282 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 }
4284 }
4285 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004286 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 ai.packageName +
4288 " while loading content provider " +
4289 info.name);
4290 return null;
4291 }
4292 try {
4293 final java.lang.ClassLoader cl = c.getClassLoader();
4294 localProvider = (ContentProvider)cl.
4295 loadClass(info.name).newInstance();
4296 provider = localProvider.getIContentProvider();
4297 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004298 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 info.name + " from sourceDir " +
4300 info.applicationInfo.sourceDir);
4301 return null;
4302 }
Joe Onorato43a17652011-04-06 19:22:23 -07004303 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 TAG, "Instantiating local provider " + info.name);
4305 // XXX Need to create the correct context for this provider.
4306 localProvider.attachInfo(c, info);
4307 } catch (java.lang.Exception e) {
4308 if (!mInstrumentation.onException(null, e)) {
4309 throw new RuntimeException(
4310 "Unable to get provider " + info.name
4311 + ": " + e.toString(), e);
4312 }
4313 return null;
4314 }
4315 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004316 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 + info.name);
4318 }
4319
4320 synchronized (mProviderMap) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004321 // There is a possibility that this thread raced with another thread to
4322 // add the provider. If we find another thread got there first then we
4323 // just get out of the way and return the original provider.
4324 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 String names[] = PATTERN_SEMICOLON.split(info.authority);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004326 for (int i = 0; i < names.length; i++) {
4327 ProviderClientRecord pr = mProviderMap.get(names[i]);
4328 if (pr != null) {
4329 if (localLOGV) {
4330 Slog.v(TAG, "installProvider: lost the race, "
4331 + "using existing named provider");
4332 }
4333 provider = pr.mProvider;
4334 } else {
4335 pr = new ProviderClientRecord(names[i], provider, localProvider);
4336 if (localProvider == null) {
4337 try {
4338 jBinder.linkToDeath(pr, 0);
4339 } catch (RemoteException e) {
4340 // Provider already dead. Bail out of here without making
4341 // any changes to the provider map or other data structures.
4342 return null;
4343 }
4344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 mProviderMap.put(names[i], pr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346 }
4347 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 if (localProvider != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004350 ProviderClientRecord pr = mLocalProviders.get(jBinder);
4351 if (pr != null) {
4352 if (localLOGV) {
4353 Slog.v(TAG, "installProvider: lost the race, "
4354 + "using existing local provider");
4355 }
4356 provider = pr.mProvider;
4357 } else {
4358 pr = new ProviderClientRecord(null, provider, localProvider);
4359 mLocalProviders.put(jBinder, pr);
4360 }
4361 }
4362
4363 if (!noReleaseNeeded) {
4364 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4365 if (prc != null) {
4366 if (localLOGV) {
4367 Slog.v(TAG, "installProvider: lost the race, incrementing ref count");
4368 }
4369 prc.count += 1;
4370 if (prc.count == 1) {
4371 if (localLOGV) {
4372 Slog.v(TAG, "installProvider: "
4373 + "snatched provider from the jaws of death");
4374 }
4375 // Because the provider previously had a reference count of zero,
4376 // it was scheduled to be removed. Cancel that.
4377 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4378 }
4379 } else {
4380 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 }
4383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 return provider;
4385 }
4386
Romain Guy65b345f2011-07-27 18:51:50 -07004387 private void attach(boolean system) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 sThreadLocal.set(this);
4389 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07004391 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004392 public void run() {
4393 ensureJitEnabled();
4394 }
4395 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4397 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4398 IActivityManager mgr = ActivityManagerNative.getDefault();
4399 try {
4400 mgr.attachApplication(mAppThread);
4401 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07004402 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 }
4404 } else {
4405 // Don't set application object here -- if the system crashes,
4406 // we can't display an alert, we just want to die die die.
4407 android.ddm.DdmHandleAppName.setAppName("system_process");
4408 try {
4409 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08004410 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 context.init(getSystemContext().mPackageInfo, null, this);
4412 Application app = Instrumentation.newApplication(Application.class, context);
4413 mAllApplications.add(app);
4414 mInitialApplication = app;
4415 app.onCreate();
4416 } catch (Exception e) {
4417 throw new RuntimeException(
4418 "Unable to instantiate Application():" + e.toString(), e);
4419 }
4420 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004421
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004422 ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004423 public void onConfigurationChanged(Configuration newConfig) {
4424 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004425 // We need to apply this change to the resources
4426 // immediately, because upon returning the view
4427 // hierarchy will be informed about it.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004428 if (applyConfigurationToResourcesLocked(newConfig, null)) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004429 // This actually changed the resources! Tell
4430 // everyone about it.
4431 if (mPendingConfiguration == null ||
4432 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
4433 mPendingConfiguration = newConfig;
4434
4435 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
4436 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004437 }
4438 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004439 }
4440 public void onLowMemory() {
4441 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004442 public void onTrimMemory(int level) {
4443 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004444 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 }
4446
Romain Guy5e9120d2012-01-30 12:17:22 -08004447 public static ActivityThread systemMain() {
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004448 HardwareRenderer.disable(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004449 ActivityThread thread = new ActivityThread();
4450 thread.attach(true);
4451 return thread;
4452 }
4453
Jeff Brown10e89712011-07-08 18:52:57 -07004454 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07004456 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 }
4458 }
4459
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004460 public int getIntCoreSetting(String key, int defaultValue) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004461 synchronized (mPackages) {
4462 if (mCoreSettings != null) {
4463 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004464 } else {
4465 return defaultValue;
4466 }
4467 }
4468 }
4469
Romain Guy65b345f2011-07-27 18:51:50 -07004470 public static void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004471 SamplingProfilerIntegration.start();
4472
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08004473 // CloseGuard defaults to true and can be quite spammy. We
4474 // disable it here, but selectively enable it later (via
4475 // StrictMode) on debug builds, but using DropBox, not logs.
4476 CloseGuard.setEnabled(false);
4477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 Process.setArgV0("<pre-initialized>");
4479
4480 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004481 if (sMainThreadHandler == null) {
4482 sMainThreadHandler = new Handler();
4483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484
4485 ActivityThread thread = new ActivityThread();
4486 thread.attach(false);
4487
Romain Guy5e9120d2012-01-30 12:17:22 -08004488 AsyncTask.init();
4489
Dianne Hackborn287952c2010-09-22 22:34:31 -07004490 if (false) {
4491 Looper.myLooper().setMessageLogging(new
4492 LogPrinter(Log.DEBUG, "ActivityThread"));
4493 }
4494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 Looper.loop();
4496
Jeff Brown10e89712011-07-08 18:52:57 -07004497 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 }
4499}