blob: 13cc3bad73882ff2cc954c2ef277f26b84408435 [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
19import android.content.BroadcastReceiver;
20import android.content.ComponentCallbacks;
21import android.content.ComponentName;
22import android.content.ContentProvider;
23import android.content.Context;
24import android.content.IContentProvider;
25import android.content.Intent;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070026import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.ServiceConnection;
28import android.content.pm.ActivityInfo;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.IPackageManager;
31import android.content.pm.InstrumentationInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.ProviderInfo;
34import android.content.pm.ServiceInfo;
35import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070036import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.database.sqlite.SQLiteDatabase;
40import android.database.sqlite.SQLiteDebug;
41import android.graphics.Bitmap;
42import android.graphics.Canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.Bundle;
44import android.os.Debug;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Looper;
48import android.os.Message;
49import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070050import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.Process;
52import android.os.RemoteException;
53import android.os.ServiceManager;
54import android.os.SystemClock;
55import android.util.AndroidRuntimeException;
56import android.util.Config;
57import android.util.DisplayMetrics;
58import android.util.EventLog;
59import android.util.Log;
60import android.view.Display;
61import android.view.View;
62import android.view.ViewDebug;
63import android.view.ViewManager;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080064import android.view.ViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.view.Window;
66import android.view.WindowManager;
67import android.view.WindowManagerImpl;
68
69import com.android.internal.os.BinderInternal;
70import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070071import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import com.android.internal.util.ArrayUtils;
73
74import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
75
76import java.io.File;
77import java.io.FileDescriptor;
78import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070079import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import java.io.PrintWriter;
81import java.lang.ref.WeakReference;
82import java.util.ArrayList;
83import java.util.HashMap;
84import java.util.Iterator;
85import java.util.List;
86import java.util.Locale;
87import java.util.Map;
88import java.util.TimeZone;
89import java.util.regex.Pattern;
90
Bob Leee5408332009-09-04 18:31:17 -070091import dalvik.system.SamplingProfiler;
92
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093final class IntentReceiverLeaked extends AndroidRuntimeException {
94 public IntentReceiverLeaked(String msg) {
95 super(msg);
96 }
97}
98
99final class ServiceConnectionLeaked extends AndroidRuntimeException {
100 public ServiceConnectionLeaked(String msg) {
101 super(msg);
102 }
103}
104
105final class SuperNotCalledException extends AndroidRuntimeException {
106 public SuperNotCalledException(String msg) {
107 super(msg);
108 }
109}
110
111/**
112 * This manages the execution of the main thread in an
113 * application process, scheduling and executing activities,
114 * broadcasts, and other operations on it as the activity
115 * manager requests.
116 *
117 * {@hide}
118 */
119public final class ActivityThread {
120 private static final String TAG = "ActivityThread";
121 private static final boolean DEBUG = false;
122 private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
123 private static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700124 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700125 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700126 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
128 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
129 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
130 private static final int LOG_ON_PAUSE_CALLED = 30021;
131 private static final int LOG_ON_RESUME_CALLED = 30022;
132
Bob Leee5408332009-09-04 18:31:17 -0700133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 public static final ActivityThread currentActivityThread() {
135 return (ActivityThread)sThreadLocal.get();
136 }
137
138 public static final String currentPackageName()
139 {
140 ActivityThread am = currentActivityThread();
141 return (am != null && am.mBoundApplication != null)
142 ? am.mBoundApplication.processName : null;
143 }
144
145 public static IPackageManager getPackageManager() {
146 if (sPackageManager != null) {
147 //Log.v("PackageManager", "returning cur default = " + sPackageManager);
148 return sPackageManager;
149 }
150 IBinder b = ServiceManager.getService("package");
151 //Log.v("PackageManager", "default service binder = " + b);
152 sPackageManager = IPackageManager.Stub.asInterface(b);
153 //Log.v("PackageManager", "default service = " + sPackageManager);
154 return sPackageManager;
155 }
156
157 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
158 if (mDisplayMetrics != null && !forceUpdate) {
159 return mDisplayMetrics;
160 }
161 if (mDisplay == null) {
162 WindowManager wm = WindowManagerImpl.getDefault();
163 mDisplay = wm.getDefaultDisplay();
164 }
165 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
166 mDisplay.getMetrics(metrics);
167 //Log.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
168 // + metrics.heightPixels + " den=" + metrics.density
169 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
170 return metrics;
171 }
172
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700173 /**
174 * Creates the top level Resources for applications with the given compatibility info.
175 *
176 * @param resDir the resource directory.
177 * @param compInfo the compability info. It will use the default compatibility info when it's
178 * null.
179 */
180 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
Dianne Hackbornf9315202009-11-17 18:28:55 -0800181 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
182 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 synchronized (mPackages) {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700184 // Resources is app scale dependent.
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700185 if (false) {
186 Log.w(TAG, "getTopLevelResources: " + resDir + " / "
187 + compInfo.applicationScale);
188 }
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700189 WeakReference<Resources> wr = mActiveResources.get(key);
Dianne Hackbornf9315202009-11-17 18:28:55 -0800190 r = wr != null ? wr.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 if (r != null && r.getAssets().isUpToDate()) {
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700192 if (false) {
193 Log.w(TAG, "Returning cached resources " + r + " " + resDir
194 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 return r;
197 }
Dianne Hackbornf9315202009-11-17 18:28:55 -0800198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
Dianne Hackbornf9315202009-11-17 18:28:55 -0800200 //if (r != null) {
201 // Log.w(TAG, "Throwing away out-of-date resources!!!! "
202 // + r + " " + resDir);
203 //}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Dianne Hackbornf9315202009-11-17 18:28:55 -0800205 AssetManager assets = new AssetManager();
206 if (assets.addAssetPath(resDir) == 0) {
207 return null;
208 }
209
210 //Log.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
211 DisplayMetrics metrics = getDisplayMetricsLocked(false);
212 r = new Resources(assets, metrics, getConfiguration(), compInfo);
213 if (false) {
214 Log.i(TAG, "Created app resources " + resDir + " " + r + ": "
215 + r.getConfiguration() + " appScale="
216 + r.getCompatibilityInfo().applicationScale);
217 }
218
219 synchronized (mPackages) {
220 WeakReference<Resources> wr = mActiveResources.get(key);
221 Resources existing = wr != null ? wr.get() : null;
222 if (existing != null && existing.getAssets().isUpToDate()) {
223 // Someone else already created the resources while we were
224 // unlocked; go ahead and use theirs.
225 r.getAssets().close();
226 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 }
Dianne Hackbornf9315202009-11-17 18:28:55 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // XXX need to remove entries when weak references go away
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700230 mActiveResources.put(key, new WeakReference<Resources>(r));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 return r;
232 }
233 }
234
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700235 /**
236 * Creates the top level resources for the given package.
237 */
238 Resources getTopLevelResources(String resDir, PackageInfo pkgInfo) {
239 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
240 }
241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 final Handler getHandler() {
243 return mH;
244 }
245
246 public final static class PackageInfo {
247
248 private final ActivityThread mActivityThread;
249 private final ApplicationInfo mApplicationInfo;
250 private final String mPackageName;
251 private final String mAppDir;
252 private final String mResDir;
253 private final String[] mSharedLibraries;
254 private final String mDataDir;
255 private final File mDataDirFile;
256 private final ClassLoader mBaseClassLoader;
257 private final boolean mSecurityViolation;
258 private final boolean mIncludeCode;
259 private Resources mResources;
260 private ClassLoader mClassLoader;
261 private Application mApplication;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700262 private CompatibilityInfo mCompatibilityInfo;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mReceivers
265 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
266 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mUnregisteredReceivers
267 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
268 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mServices
269 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
270 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mUnboundServices
271 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
272
273 int mClientCount = 0;
274
275 public PackageInfo(ActivityThread activityThread, ApplicationInfo aInfo,
276 ActivityThread mainThread, ClassLoader baseLoader,
277 boolean securityViolation, boolean includeCode) {
278 mActivityThread = activityThread;
279 mApplicationInfo = aInfo;
280 mPackageName = aInfo.packageName;
281 mAppDir = aInfo.sourceDir;
282 mResDir = aInfo.uid == Process.myUid() ? aInfo.sourceDir
283 : aInfo.publicSourceDir;
284 mSharedLibraries = aInfo.sharedLibraryFiles;
285 mDataDir = aInfo.dataDir;
286 mDataDirFile = mDataDir != null ? new File(mDataDir) : null;
287 mBaseClassLoader = baseLoader;
288 mSecurityViolation = securityViolation;
289 mIncludeCode = includeCode;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700290 mCompatibilityInfo = new CompatibilityInfo(aInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291
292 if (mAppDir == null) {
293 if (mSystemContext == null) {
294 mSystemContext =
Dianne Hackborn21556372010-02-04 16:34:40 -0800295 ContextImpl.createSystemContext(mainThread);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 mSystemContext.getResources().updateConfiguration(
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700297 mainThread.getConfiguration(),
298 mainThread.getDisplayMetricsLocked(false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 //Log.i(TAG, "Created system resources "
300 // + mSystemContext.getResources() + ": "
301 // + mSystemContext.getResources().getConfiguration());
302 }
303 mClassLoader = mSystemContext.getClassLoader();
304 mResources = mSystemContext.getResources();
305 }
306 }
307
308 public PackageInfo(ActivityThread activityThread, String name,
Mike Cleron432b7132009-09-24 15:28:29 -0700309 Context systemContext, ApplicationInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 mActivityThread = activityThread;
Mike Cleron432b7132009-09-24 15:28:29 -0700311 mApplicationInfo = info != null ? info : new ApplicationInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 mApplicationInfo.packageName = name;
313 mPackageName = name;
314 mAppDir = null;
315 mResDir = null;
316 mSharedLibraries = null;
317 mDataDir = null;
318 mDataDirFile = null;
319 mBaseClassLoader = null;
320 mSecurityViolation = false;
321 mIncludeCode = true;
322 mClassLoader = systemContext.getClassLoader();
323 mResources = systemContext.getResources();
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700324 mCompatibilityInfo = new CompatibilityInfo(mApplicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 }
326
327 public String getPackageName() {
328 return mPackageName;
329 }
330
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700331 public ApplicationInfo getApplicationInfo() {
332 return mApplicationInfo;
333 }
Bob Leee5408332009-09-04 18:31:17 -0700334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 public boolean isSecurityViolation() {
336 return mSecurityViolation;
337 }
338
339 /**
340 * Gets the array of shared libraries that are listed as
341 * used by the given package.
Bob Leee5408332009-09-04 18:31:17 -0700342 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 * @param packageName the name of the package (note: not its
344 * file name)
345 * @return null-ok; the array of shared libraries, each one
346 * a fully-qualified path
347 */
348 private static String[] getLibrariesFor(String packageName) {
349 ApplicationInfo ai = null;
350 try {
351 ai = getPackageManager().getApplicationInfo(packageName,
352 PackageManager.GET_SHARED_LIBRARY_FILES);
353 } catch (RemoteException e) {
354 throw new AssertionError(e);
355 }
356
357 if (ai == null) {
358 return null;
359 }
360
361 return ai.sharedLibraryFiles;
362 }
363
364 /**
365 * Combines two arrays (of library names) such that they are
366 * concatenated in order but are devoid of duplicates. The
367 * result is a single string with the names of the libraries
368 * separated by colons, or <code>null</code> if both lists
369 * were <code>null</code> or empty.
Bob Leee5408332009-09-04 18:31:17 -0700370 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 * @param list1 null-ok; the first list
372 * @param list2 null-ok; the second list
373 * @return null-ok; the combination
374 */
375 private static String combineLibs(String[] list1, String[] list2) {
376 StringBuilder result = new StringBuilder(300);
377 boolean first = true;
378
379 if (list1 != null) {
380 for (String s : list1) {
381 if (first) {
382 first = false;
383 } else {
384 result.append(':');
385 }
386 result.append(s);
387 }
388 }
389
390 // Only need to check for duplicates if list1 was non-empty.
391 boolean dupCheck = !first;
392
393 if (list2 != null) {
394 for (String s : list2) {
395 if (dupCheck && ArrayUtils.contains(list1, s)) {
396 continue;
397 }
Bob Leee5408332009-09-04 18:31:17 -0700398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 if (first) {
400 first = false;
401 } else {
402 result.append(':');
403 }
404 result.append(s);
405 }
406 }
407
408 return result.toString();
409 }
Bob Leee5408332009-09-04 18:31:17 -0700410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 public ClassLoader getClassLoader() {
412 synchronized (this) {
413 if (mClassLoader != null) {
414 return mClassLoader;
415 }
416
417 if (mIncludeCode && !mPackageName.equals("android")) {
418 String zip = mAppDir;
419
420 /*
421 * The following is a bit of a hack to inject
422 * instrumentation into the system: If the app
423 * being started matches one of the instrumentation names,
424 * then we combine both the "instrumentation" and
425 * "instrumented" app into the path, along with the
426 * concatenation of both apps' shared library lists.
427 */
428
429 String instrumentationAppDir =
430 mActivityThread.mInstrumentationAppDir;
431 String instrumentationAppPackage =
432 mActivityThread.mInstrumentationAppPackage;
433 String instrumentedAppDir =
434 mActivityThread.mInstrumentedAppDir;
435 String[] instrumentationLibs = null;
436
437 if (mAppDir.equals(instrumentationAppDir)
438 || mAppDir.equals(instrumentedAppDir)) {
439 zip = instrumentationAppDir + ":" + instrumentedAppDir;
440 if (! instrumentedAppDir.equals(instrumentationAppDir)) {
441 instrumentationLibs =
442 getLibrariesFor(instrumentationAppPackage);
443 }
444 }
445
446 if ((mSharedLibraries != null) ||
447 (instrumentationLibs != null)) {
Bob Leee5408332009-09-04 18:31:17 -0700448 zip =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 combineLibs(mSharedLibraries, instrumentationLibs)
450 + ':' + zip;
451 }
452
453 /*
454 * With all the combination done (if necessary, actually
455 * create the class loader.
456 */
457
458 if (localLOGV) Log.v(TAG, "Class path: " + zip);
459
460 mClassLoader =
461 ApplicationLoaders.getDefault().getClassLoader(
462 zip, mDataDir, mBaseClassLoader);
463 } else {
464 if (mBaseClassLoader == null) {
465 mClassLoader = ClassLoader.getSystemClassLoader();
466 } else {
467 mClassLoader = mBaseClassLoader;
468 }
469 }
470 return mClassLoader;
471 }
472 }
473
474 public String getAppDir() {
475 return mAppDir;
476 }
477
478 public String getResDir() {
479 return mResDir;
480 }
481
482 public String getDataDir() {
483 return mDataDir;
484 }
485
486 public File getDataDirFile() {
487 return mDataDirFile;
488 }
489
490 public AssetManager getAssets(ActivityThread mainThread) {
491 return getResources(mainThread).getAssets();
492 }
493
494 public Resources getResources(ActivityThread mainThread) {
495 if (mResources == null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700496 mResources = mainThread.getTopLevelResources(mResDir, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 }
498 return mResources;
499 }
500
Dianne Hackborn0be1f782009-11-09 12:30:12 -0800501 public Application makeApplication(boolean forceDefaultAppClass,
502 Instrumentation instrumentation) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 if (mApplication != null) {
504 return mApplication;
505 }
Bob Leee5408332009-09-04 18:31:17 -0700506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 Application app = null;
Bob Leee5408332009-09-04 18:31:17 -0700508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 String appClass = mApplicationInfo.className;
Christopher Tate181fafa2009-05-14 11:12:14 -0700510 if (forceDefaultAppClass || (appClass == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 appClass = "android.app.Application";
512 }
513
514 try {
515 java.lang.ClassLoader cl = getClassLoader();
Dianne Hackborn21556372010-02-04 16:34:40 -0800516 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 appContext.init(this, null, mActivityThread);
518 app = mActivityThread.mInstrumentation.newApplication(
519 cl, appClass, appContext);
520 appContext.setOuterContext(app);
521 } catch (Exception e) {
522 if (!mActivityThread.mInstrumentation.onException(app, e)) {
523 throw new RuntimeException(
524 "Unable to instantiate application " + appClass
525 + ": " + e.toString(), e);
526 }
527 }
528 mActivityThread.mAllApplications.add(app);
Dianne Hackborn0be1f782009-11-09 12:30:12 -0800529 mApplication = app;
530
531 if (instrumentation != null) {
532 try {
533 instrumentation.callApplicationOnCreate(app);
534 } catch (Exception e) {
535 if (!instrumentation.onException(app, e)) {
536 throw new RuntimeException(
537 "Unable to create application " + app.getClass().getName()
538 + ": " + e.toString(), e);
539 }
540 }
541 }
542
543 return app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 }
Bob Leee5408332009-09-04 18:31:17 -0700545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 public void removeContextRegistrations(Context context,
547 String who, String what) {
548 HashMap<BroadcastReceiver, ReceiverDispatcher> rmap =
549 mReceivers.remove(context);
550 if (rmap != null) {
551 Iterator<ReceiverDispatcher> it = rmap.values().iterator();
552 while (it.hasNext()) {
553 ReceiverDispatcher rd = it.next();
554 IntentReceiverLeaked leak = new IntentReceiverLeaked(
555 what + " " + who + " has leaked IntentReceiver "
556 + rd.getIntentReceiver() + " that was " +
557 "originally registered here. Are you missing a " +
558 "call to unregisterReceiver()?");
559 leak.setStackTrace(rd.getLocation().getStackTrace());
560 Log.e(TAG, leak.getMessage(), leak);
561 try {
562 ActivityManagerNative.getDefault().unregisterReceiver(
563 rd.getIIntentReceiver());
564 } catch (RemoteException e) {
565 // system crashed, nothing we can do
566 }
567 }
568 }
569 mUnregisteredReceivers.remove(context);
570 //Log.i(TAG, "Receiver registrations: " + mReceivers);
571 HashMap<ServiceConnection, ServiceDispatcher> smap =
572 mServices.remove(context);
573 if (smap != null) {
574 Iterator<ServiceDispatcher> it = smap.values().iterator();
575 while (it.hasNext()) {
576 ServiceDispatcher sd = it.next();
577 ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
578 what + " " + who + " has leaked ServiceConnection "
579 + sd.getServiceConnection() + " that was originally bound here");
580 leak.setStackTrace(sd.getLocation().getStackTrace());
581 Log.e(TAG, leak.getMessage(), leak);
582 try {
583 ActivityManagerNative.getDefault().unbindService(
584 sd.getIServiceConnection());
585 } catch (RemoteException e) {
586 // system crashed, nothing we can do
587 }
588 sd.doForget();
589 }
590 }
591 mUnboundServices.remove(context);
592 //Log.i(TAG, "Service registrations: " + mServices);
593 }
594
595 public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,
596 Context context, Handler handler,
597 Instrumentation instrumentation, boolean registered) {
598 synchronized (mReceivers) {
599 ReceiverDispatcher rd = null;
600 HashMap<BroadcastReceiver, ReceiverDispatcher> map = null;
601 if (registered) {
602 map = mReceivers.get(context);
603 if (map != null) {
604 rd = map.get(r);
605 }
606 }
607 if (rd == null) {
608 rd = new ReceiverDispatcher(r, context, handler,
609 instrumentation, registered);
610 if (registered) {
611 if (map == null) {
612 map = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
613 mReceivers.put(context, map);
614 }
615 map.put(r, rd);
616 }
617 } else {
618 rd.validate(context, handler);
619 }
620 return rd.getIIntentReceiver();
621 }
622 }
623
624 public IIntentReceiver forgetReceiverDispatcher(Context context,
625 BroadcastReceiver r) {
626 synchronized (mReceivers) {
627 HashMap<BroadcastReceiver, ReceiverDispatcher> map = mReceivers.get(context);
628 ReceiverDispatcher rd = null;
629 if (map != null) {
630 rd = map.get(r);
631 if (rd != null) {
632 map.remove(r);
633 if (map.size() == 0) {
634 mReceivers.remove(context);
635 }
636 if (r.getDebugUnregister()) {
637 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
638 = mUnregisteredReceivers.get(context);
639 if (holder == null) {
640 holder = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
641 mUnregisteredReceivers.put(context, holder);
642 }
643 RuntimeException ex = new IllegalArgumentException(
644 "Originally unregistered here:");
645 ex.fillInStackTrace();
646 rd.setUnregisterLocation(ex);
647 holder.put(r, rd);
648 }
649 return rd.getIIntentReceiver();
650 }
651 }
652 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
653 = mUnregisteredReceivers.get(context);
654 if (holder != null) {
655 rd = holder.get(r);
656 if (rd != null) {
657 RuntimeException ex = rd.getUnregisterLocation();
658 throw new IllegalArgumentException(
659 "Unregistering Receiver " + r
660 + " that was already unregistered", ex);
661 }
662 }
663 if (context == null) {
664 throw new IllegalStateException("Unbinding Receiver " + r
665 + " from Context that is no longer in use: " + context);
666 } else {
667 throw new IllegalArgumentException("Receiver not registered: " + r);
668 }
669
670 }
671 }
672
673 static final class ReceiverDispatcher {
674
675 final static class InnerReceiver extends IIntentReceiver.Stub {
676 final WeakReference<ReceiverDispatcher> mDispatcher;
677 final ReceiverDispatcher mStrongRef;
Bob Leee5408332009-09-04 18:31:17 -0700678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 InnerReceiver(ReceiverDispatcher rd, boolean strong) {
680 mDispatcher = new WeakReference<ReceiverDispatcher>(rd);
681 mStrongRef = strong ? rd : null;
682 }
683 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700684 String data, Bundle extras, boolean ordered, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 ReceiverDispatcher rd = mDispatcher.get();
686 if (DEBUG_BROADCAST) {
687 int seq = intent.getIntExtra("seq", -1);
688 Log.i(TAG, "Receiving broadcast " + intent.getAction() + " seq=" + seq
689 + " to " + rd);
690 }
691 if (rd != null) {
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700692 rd.performReceive(intent, resultCode, data, extras,
693 ordered, sticky);
Christopher Tate08a46252009-12-08 13:48:45 -0800694 } else {
695 // The activity manager dispatched a broadcast to a registered
696 // receiver in this process, but before it could be delivered the
697 // receiver was unregistered. Acknowledge the broadcast on its
698 // behalf so that the system's broadcast sequence can continue.
699 if (DEBUG_BROADCAST) {
700 Log.i(TAG, "Broadcast to unregistered receiver");
701 }
702 IActivityManager mgr = ActivityManagerNative.getDefault();
703 try {
704 mgr.finishReceiver(this, resultCode, data, extras, false);
705 } catch (RemoteException e) {
706 Log.w(TAG, "Couldn't finish broadcast to unregistered receiver");
707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 }
709 }
710 }
Bob Leee5408332009-09-04 18:31:17 -0700711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 final IIntentReceiver.Stub mIIntentReceiver;
713 final BroadcastReceiver mReceiver;
714 final Context mContext;
715 final Handler mActivityThread;
716 final Instrumentation mInstrumentation;
717 final boolean mRegistered;
718 final IntentReceiverLeaked mLocation;
719 RuntimeException mUnregisterLocation;
720
721 final class Args implements Runnable {
722 private Intent mCurIntent;
723 private int mCurCode;
724 private String mCurData;
725 private Bundle mCurMap;
726 private boolean mCurOrdered;
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700727 private boolean mCurSticky;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728
729 public void run() {
730 BroadcastReceiver receiver = mReceiver;
731 if (DEBUG_BROADCAST) {
732 int seq = mCurIntent.getIntExtra("seq", -1);
Christopher Tate08a46252009-12-08 13:48:45 -0800733 Log.i(TAG, "Dispatching broadcast " + mCurIntent.getAction()
734 + " seq=" + seq + " to " + mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 }
736 if (receiver == null) {
737 return;
738 }
739
740 IActivityManager mgr = ActivityManagerNative.getDefault();
741 Intent intent = mCurIntent;
742 mCurIntent = null;
743 try {
744 ClassLoader cl = mReceiver.getClass().getClassLoader();
745 intent.setExtrasClassLoader(cl);
746 if (mCurMap != null) {
747 mCurMap.setClassLoader(cl);
748 }
749 receiver.setOrderedHint(true);
750 receiver.setResult(mCurCode, mCurData, mCurMap);
751 receiver.clearAbortBroadcast();
752 receiver.setOrderedHint(mCurOrdered);
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700753 receiver.setInitialStickyHint(mCurSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 receiver.onReceive(mContext, intent);
755 } catch (Exception e) {
756 if (mRegistered && mCurOrdered) {
757 try {
758 mgr.finishReceiver(mIIntentReceiver,
759 mCurCode, mCurData, mCurMap, false);
760 } catch (RemoteException ex) {
761 }
762 }
763 if (mInstrumentation == null ||
764 !mInstrumentation.onException(mReceiver, e)) {
765 throw new RuntimeException(
766 "Error receiving broadcast " + intent
767 + " in " + mReceiver, e);
768 }
769 }
770 if (mRegistered && mCurOrdered) {
771 try {
772 mgr.finishReceiver(mIIntentReceiver,
773 receiver.getResultCode(),
774 receiver.getResultData(),
775 receiver.getResultExtras(false),
776 receiver.getAbortBroadcast());
777 } catch (RemoteException ex) {
778 }
779 }
780 }
781 }
782
783 ReceiverDispatcher(BroadcastReceiver receiver, Context context,
784 Handler activityThread, Instrumentation instrumentation,
785 boolean registered) {
786 if (activityThread == null) {
787 throw new NullPointerException("Handler must not be null");
788 }
789
790 mIIntentReceiver = new InnerReceiver(this, !registered);
791 mReceiver = receiver;
792 mContext = context;
793 mActivityThread = activityThread;
794 mInstrumentation = instrumentation;
795 mRegistered = registered;
796 mLocation = new IntentReceiverLeaked(null);
797 mLocation.fillInStackTrace();
798 }
799
800 void validate(Context context, Handler activityThread) {
801 if (mContext != context) {
802 throw new IllegalStateException(
803 "Receiver " + mReceiver +
804 " registered with differing Context (was " +
805 mContext + " now " + context + ")");
806 }
807 if (mActivityThread != activityThread) {
808 throw new IllegalStateException(
809 "Receiver " + mReceiver +
810 " registered with differing handler (was " +
811 mActivityThread + " now " + activityThread + ")");
812 }
813 }
814
815 IntentReceiverLeaked getLocation() {
816 return mLocation;
817 }
818
819 BroadcastReceiver getIntentReceiver() {
820 return mReceiver;
821 }
Bob Leee5408332009-09-04 18:31:17 -0700822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 IIntentReceiver getIIntentReceiver() {
824 return mIIntentReceiver;
825 }
826
827 void setUnregisterLocation(RuntimeException ex) {
828 mUnregisterLocation = ex;
829 }
830
831 RuntimeException getUnregisterLocation() {
832 return mUnregisterLocation;
833 }
834
835 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700836 String data, Bundle extras, boolean ordered, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 if (DEBUG_BROADCAST) {
838 int seq = intent.getIntExtra("seq", -1);
839 Log.i(TAG, "Enqueueing broadcast " + intent.getAction() + " seq=" + seq
840 + " to " + mReceiver);
841 }
842 Args args = new Args();
843 args.mCurIntent = intent;
844 args.mCurCode = resultCode;
845 args.mCurData = data;
846 args.mCurMap = extras;
847 args.mCurOrdered = ordered;
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700848 args.mCurSticky = sticky;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 if (!mActivityThread.post(args)) {
850 if (mRegistered) {
851 IActivityManager mgr = ActivityManagerNative.getDefault();
852 try {
853 mgr.finishReceiver(mIIntentReceiver, args.mCurCode,
854 args.mCurData, args.mCurMap, false);
855 } catch (RemoteException ex) {
856 }
857 }
858 }
859 }
860
861 }
862
863 public final IServiceConnection getServiceDispatcher(ServiceConnection c,
864 Context context, Handler handler, int flags) {
865 synchronized (mServices) {
866 ServiceDispatcher sd = null;
867 HashMap<ServiceConnection, ServiceDispatcher> map = mServices.get(context);
868 if (map != null) {
869 sd = map.get(c);
870 }
871 if (sd == null) {
872 sd = new ServiceDispatcher(c, context, handler, flags);
873 if (map == null) {
874 map = new HashMap<ServiceConnection, ServiceDispatcher>();
875 mServices.put(context, map);
876 }
877 map.put(c, sd);
878 } else {
879 sd.validate(context, handler);
880 }
881 return sd.getIServiceConnection();
882 }
883 }
884
885 public final IServiceConnection forgetServiceDispatcher(Context context,
886 ServiceConnection c) {
887 synchronized (mServices) {
888 HashMap<ServiceConnection, ServiceDispatcher> map
889 = mServices.get(context);
890 ServiceDispatcher sd = null;
891 if (map != null) {
892 sd = map.get(c);
893 if (sd != null) {
894 map.remove(c);
895 sd.doForget();
896 if (map.size() == 0) {
897 mServices.remove(context);
898 }
899 if ((sd.getFlags()&Context.BIND_DEBUG_UNBIND) != 0) {
900 HashMap<ServiceConnection, ServiceDispatcher> holder
901 = mUnboundServices.get(context);
902 if (holder == null) {
903 holder = new HashMap<ServiceConnection, ServiceDispatcher>();
904 mUnboundServices.put(context, holder);
905 }
906 RuntimeException ex = new IllegalArgumentException(
907 "Originally unbound here:");
908 ex.fillInStackTrace();
909 sd.setUnbindLocation(ex);
910 holder.put(c, sd);
911 }
912 return sd.getIServiceConnection();
913 }
914 }
915 HashMap<ServiceConnection, ServiceDispatcher> holder
916 = mUnboundServices.get(context);
917 if (holder != null) {
918 sd = holder.get(c);
919 if (sd != null) {
920 RuntimeException ex = sd.getUnbindLocation();
921 throw new IllegalArgumentException(
922 "Unbinding Service " + c
923 + " that was already unbound", ex);
924 }
925 }
926 if (context == null) {
927 throw new IllegalStateException("Unbinding Service " + c
928 + " from Context that is no longer in use: " + context);
929 } else {
930 throw new IllegalArgumentException("Service not registered: " + c);
931 }
932 }
933 }
934
935 static final class ServiceDispatcher {
936 private final InnerConnection mIServiceConnection;
937 private final ServiceConnection mConnection;
938 private final Context mContext;
939 private final Handler mActivityThread;
940 private final ServiceConnectionLeaked mLocation;
941 private final int mFlags;
942
943 private RuntimeException mUnbindLocation;
944
945 private boolean mDied;
946
947 private static class ConnectionInfo {
948 IBinder binder;
949 IBinder.DeathRecipient deathMonitor;
950 }
951
952 private static class InnerConnection extends IServiceConnection.Stub {
953 final WeakReference<ServiceDispatcher> mDispatcher;
Bob Leee5408332009-09-04 18:31:17 -0700954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 InnerConnection(ServiceDispatcher sd) {
956 mDispatcher = new WeakReference<ServiceDispatcher>(sd);
957 }
958
959 public void connected(ComponentName name, IBinder service) throws RemoteException {
960 ServiceDispatcher sd = mDispatcher.get();
961 if (sd != null) {
962 sd.connected(name, service);
963 }
964 }
965 }
Bob Leee5408332009-09-04 18:31:17 -0700966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 private final HashMap<ComponentName, ConnectionInfo> mActiveConnections
968 = new HashMap<ComponentName, ConnectionInfo>();
969
970 ServiceDispatcher(ServiceConnection conn,
971 Context context, Handler activityThread, int flags) {
972 mIServiceConnection = new InnerConnection(this);
973 mConnection = conn;
974 mContext = context;
975 mActivityThread = activityThread;
976 mLocation = new ServiceConnectionLeaked(null);
977 mLocation.fillInStackTrace();
978 mFlags = flags;
979 }
980
981 void validate(Context context, Handler activityThread) {
982 if (mContext != context) {
983 throw new RuntimeException(
984 "ServiceConnection " + mConnection +
985 " registered with differing Context (was " +
986 mContext + " now " + context + ")");
987 }
988 if (mActivityThread != activityThread) {
989 throw new RuntimeException(
990 "ServiceConnection " + mConnection +
991 " registered with differing handler (was " +
992 mActivityThread + " now " + activityThread + ")");
993 }
994 }
995
996 void doForget() {
997 synchronized(this) {
998 Iterator<ConnectionInfo> it = mActiveConnections.values().iterator();
999 while (it.hasNext()) {
1000 ConnectionInfo ci = it.next();
1001 ci.binder.unlinkToDeath(ci.deathMonitor, 0);
1002 }
1003 mActiveConnections.clear();
1004 }
1005 }
1006
1007 ServiceConnectionLeaked getLocation() {
1008 return mLocation;
1009 }
1010
1011 ServiceConnection getServiceConnection() {
1012 return mConnection;
1013 }
1014
1015 IServiceConnection getIServiceConnection() {
1016 return mIServiceConnection;
1017 }
Bob Leee5408332009-09-04 18:31:17 -07001018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 int getFlags() {
1020 return mFlags;
1021 }
1022
1023 void setUnbindLocation(RuntimeException ex) {
1024 mUnbindLocation = ex;
1025 }
1026
1027 RuntimeException getUnbindLocation() {
1028 return mUnbindLocation;
1029 }
1030
1031 public void connected(ComponentName name, IBinder service) {
1032 if (mActivityThread != null) {
1033 mActivityThread.post(new RunConnection(name, service, 0));
1034 } else {
1035 doConnected(name, service);
1036 }
1037 }
1038
1039 public void death(ComponentName name, IBinder service) {
1040 ConnectionInfo old;
1041
1042 synchronized (this) {
1043 mDied = true;
1044 old = mActiveConnections.remove(name);
1045 if (old == null || old.binder != service) {
1046 // Death for someone different than who we last
1047 // reported... just ignore it.
1048 return;
1049 }
1050 old.binder.unlinkToDeath(old.deathMonitor, 0);
1051 }
1052
1053 if (mActivityThread != null) {
1054 mActivityThread.post(new RunConnection(name, service, 1));
1055 } else {
1056 doDeath(name, service);
1057 }
1058 }
1059
1060 public void doConnected(ComponentName name, IBinder service) {
1061 ConnectionInfo old;
1062 ConnectionInfo info;
1063
1064 synchronized (this) {
1065 old = mActiveConnections.get(name);
1066 if (old != null && old.binder == service) {
1067 // Huh, already have this one. Oh well!
1068 return;
1069 }
1070
1071 if (service != null) {
1072 // A new service is being connected... set it all up.
1073 mDied = false;
1074 info = new ConnectionInfo();
1075 info.binder = service;
1076 info.deathMonitor = new DeathMonitor(name, service);
1077 try {
1078 service.linkToDeath(info.deathMonitor, 0);
1079 mActiveConnections.put(name, info);
1080 } catch (RemoteException e) {
1081 // This service was dead before we got it... just
1082 // don't do anything with it.
1083 mActiveConnections.remove(name);
1084 return;
1085 }
1086
1087 } else {
1088 // The named service is being disconnected... clean up.
1089 mActiveConnections.remove(name);
1090 }
1091
1092 if (old != null) {
1093 old.binder.unlinkToDeath(old.deathMonitor, 0);
1094 }
1095 }
1096
1097 // If there was an old service, it is not disconnected.
1098 if (old != null) {
1099 mConnection.onServiceDisconnected(name);
1100 }
1101 // If there is a new service, it is now connected.
1102 if (service != null) {
1103 mConnection.onServiceConnected(name, service);
1104 }
1105 }
1106
1107 public void doDeath(ComponentName name, IBinder service) {
1108 mConnection.onServiceDisconnected(name);
1109 }
1110
1111 private final class RunConnection implements Runnable {
1112 RunConnection(ComponentName name, IBinder service, int command) {
1113 mName = name;
1114 mService = service;
1115 mCommand = command;
1116 }
1117
1118 public void run() {
1119 if (mCommand == 0) {
1120 doConnected(mName, mService);
1121 } else if (mCommand == 1) {
1122 doDeath(mName, mService);
1123 }
1124 }
1125
1126 final ComponentName mName;
1127 final IBinder mService;
1128 final int mCommand;
1129 }
1130
1131 private final class DeathMonitor implements IBinder.DeathRecipient
1132 {
1133 DeathMonitor(ComponentName name, IBinder service) {
1134 mName = name;
1135 mService = service;
1136 }
1137
1138 public void binderDied() {
1139 death(mName, mService);
1140 }
1141
1142 final ComponentName mName;
1143 final IBinder mService;
1144 }
1145 }
1146 }
1147
Dianne Hackborn21556372010-02-04 16:34:40 -08001148 private static ContextImpl mSystemContext = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149
1150 private static final class ActivityRecord {
1151 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001152 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 Intent intent;
1154 Bundle state;
1155 Activity activity;
1156 Window window;
1157 Activity parent;
1158 String embeddedID;
1159 Object lastNonConfigurationInstance;
1160 HashMap<String,Object> lastNonConfigurationChildInstances;
1161 boolean paused;
1162 boolean stopped;
1163 boolean hideForNow;
1164 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -07001165 Configuration createdConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 ActivityRecord nextIdle;
1167
1168 ActivityInfo activityInfo;
1169 PackageInfo packageInfo;
1170
1171 List<ResultInfo> pendingResults;
1172 List<Intent> pendingIntents;
1173
1174 boolean startsNotResumed;
1175 boolean isForward;
1176
1177 ActivityRecord() {
1178 parent = null;
1179 embeddedID = null;
1180 paused = false;
1181 stopped = false;
1182 hideForNow = false;
1183 nextIdle = null;
1184 }
1185
1186 public String toString() {
1187 ComponentName componentName = intent.getComponent();
1188 return "ActivityRecord{"
1189 + Integer.toHexString(System.identityHashCode(this))
1190 + " token=" + token + " " + (componentName == null
1191 ? "no component name" : componentName.toShortString())
1192 + "}";
1193 }
1194 }
1195
1196 private final class ProviderRecord implements IBinder.DeathRecipient {
1197 final String mName;
1198 final IContentProvider mProvider;
1199 final ContentProvider mLocalProvider;
1200
1201 ProviderRecord(String name, IContentProvider provider,
1202 ContentProvider localProvider) {
1203 mName = name;
1204 mProvider = provider;
1205 mLocalProvider = localProvider;
1206 }
1207
1208 public void binderDied() {
1209 removeDeadProvider(mName, mProvider);
1210 }
1211 }
1212
1213 private static final class NewIntentData {
1214 List<Intent> intents;
1215 IBinder token;
1216 public String toString() {
1217 return "NewIntentData{intents=" + intents + " token=" + token + "}";
1218 }
1219 }
1220
1221 private static final class ReceiverData {
1222 Intent intent;
1223 ActivityInfo info;
1224 int resultCode;
1225 String resultData;
1226 Bundle resultExtras;
1227 boolean sync;
1228 boolean resultAbort;
1229 public String toString() {
1230 return "ReceiverData{intent=" + intent + " packageName=" +
1231 info.packageName + " resultCode=" + resultCode
1232 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
1233 }
1234 }
1235
Christopher Tate181fafa2009-05-14 11:12:14 -07001236 private static final class CreateBackupAgentData {
1237 ApplicationInfo appInfo;
1238 int backupMode;
1239 public String toString() {
1240 return "CreateBackupAgentData{appInfo=" + appInfo
1241 + " backupAgent=" + appInfo.backupAgentName
1242 + " mode=" + backupMode + "}";
1243 }
1244 }
Bob Leee5408332009-09-04 18:31:17 -07001245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 private static final class CreateServiceData {
1247 IBinder token;
1248 ServiceInfo info;
1249 Intent intent;
1250 public String toString() {
1251 return "CreateServiceData{token=" + token + " className="
1252 + info.name + " packageName=" + info.packageName
1253 + " intent=" + intent + "}";
1254 }
1255 }
1256
1257 private static final class BindServiceData {
1258 IBinder token;
1259 Intent intent;
1260 boolean rebind;
1261 public String toString() {
1262 return "BindServiceData{token=" + token + " intent=" + intent + "}";
1263 }
1264 }
1265
1266 private static final class ServiceArgsData {
1267 IBinder token;
1268 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001269 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 Intent args;
1271 public String toString() {
1272 return "ServiceArgsData{token=" + token + " startId=" + startId
1273 + " args=" + args + "}";
1274 }
1275 }
1276
1277 private static final class AppBindData {
1278 PackageInfo info;
1279 String processName;
1280 ApplicationInfo appInfo;
1281 List<ProviderInfo> providers;
1282 ComponentName instrumentationName;
1283 String profileFile;
1284 Bundle instrumentationArgs;
1285 IInstrumentationWatcher instrumentationWatcher;
1286 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001287 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 Configuration config;
1289 boolean handlingProfiling;
1290 public String toString() {
1291 return "AppBindData{appInfo=" + appInfo + "}";
1292 }
1293 }
1294
1295 private static final class DumpServiceInfo {
1296 FileDescriptor fd;
1297 IBinder service;
1298 String[] args;
1299 boolean dumped;
1300 }
1301
1302 private static final class ResultData {
1303 IBinder token;
1304 List<ResultInfo> results;
1305 public String toString() {
1306 return "ResultData{token=" + token + " results" + results + "}";
1307 }
1308 }
1309
1310 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -08001311 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 String what;
1313 String who;
1314 }
1315
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001316 private static final class ProfilerControlData {
1317 String path;
1318 ParcelFileDescriptor fd;
1319 }
1320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 private final class ApplicationThread extends ApplicationThreadNative {
1322 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
1323 private static final String ONE_COUNT_COLUMN = "%17s %8d";
1324 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Bob Leee5408332009-09-04 18:31:17 -07001325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 // Formatting for checkin service - update version if row format changes
1327 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -07001328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 public final void schedulePauseActivity(IBinder token, boolean finished,
1330 boolean userLeaving, int configChanges) {
1331 queueOrSendMessage(
1332 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
1333 token,
1334 (userLeaving ? 1 : 0),
1335 configChanges);
1336 }
1337
1338 public final void scheduleStopActivity(IBinder token, boolean showWindow,
1339 int configChanges) {
1340 queueOrSendMessage(
1341 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
1342 token, 0, configChanges);
1343 }
1344
1345 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
1346 queueOrSendMessage(
1347 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
1348 token);
1349 }
1350
1351 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
1352 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
1353 }
1354
1355 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
1356 ResultData res = new ResultData();
1357 res.token = token;
1358 res.results = results;
1359 queueOrSendMessage(H.SEND_RESULT, res);
1360 }
1361
1362 // we use token to identify this activity without having to send the
1363 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001364 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
1366 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
1367 ActivityRecord r = new ActivityRecord();
1368
1369 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001370 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 r.intent = intent;
1372 r.activityInfo = info;
1373 r.state = state;
1374
1375 r.pendingResults = pendingResults;
1376 r.pendingIntents = pendingNewIntents;
1377
1378 r.startsNotResumed = notResumed;
1379 r.isForward = isForward;
1380
1381 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
1382 }
1383
1384 public final void scheduleRelaunchActivity(IBinder token,
1385 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001386 int configChanges, boolean notResumed, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 ActivityRecord r = new ActivityRecord();
1388
1389 r.token = token;
1390 r.pendingResults = pendingResults;
1391 r.pendingIntents = pendingNewIntents;
1392 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001393 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001395 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 mRelaunchingActivities.add(r);
1397 }
Bob Leee5408332009-09-04 18:31:17 -07001398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
1400 }
1401
1402 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
1403 NewIntentData data = new NewIntentData();
1404 data.intents = intents;
1405 data.token = token;
1406
1407 queueOrSendMessage(H.NEW_INTENT, data);
1408 }
1409
1410 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
1411 int configChanges) {
1412 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
1413 configChanges);
1414 }
1415
1416 public final void scheduleReceiver(Intent intent, ActivityInfo info,
1417 int resultCode, String data, Bundle extras, boolean sync) {
1418 ReceiverData r = new ReceiverData();
1419
1420 r.intent = intent;
1421 r.info = info;
1422 r.resultCode = resultCode;
1423 r.resultData = data;
1424 r.resultExtras = extras;
1425 r.sync = sync;
1426
1427 queueOrSendMessage(H.RECEIVER, r);
1428 }
1429
Christopher Tate181fafa2009-05-14 11:12:14 -07001430 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
1431 CreateBackupAgentData d = new CreateBackupAgentData();
1432 d.appInfo = app;
1433 d.backupMode = backupMode;
1434
1435 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
1436 }
1437
1438 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
1439 CreateBackupAgentData d = new CreateBackupAgentData();
1440 d.appInfo = app;
1441
1442 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
1443 }
1444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 public final void scheduleCreateService(IBinder token,
1446 ServiceInfo info) {
1447 CreateServiceData s = new CreateServiceData();
1448 s.token = token;
1449 s.info = info;
1450
1451 queueOrSendMessage(H.CREATE_SERVICE, s);
1452 }
1453
1454 public final void scheduleBindService(IBinder token, Intent intent,
1455 boolean rebind) {
1456 BindServiceData s = new BindServiceData();
1457 s.token = token;
1458 s.intent = intent;
1459 s.rebind = rebind;
1460
1461 queueOrSendMessage(H.BIND_SERVICE, s);
1462 }
1463
1464 public final void scheduleUnbindService(IBinder token, Intent intent) {
1465 BindServiceData s = new BindServiceData();
1466 s.token = token;
1467 s.intent = intent;
1468
1469 queueOrSendMessage(H.UNBIND_SERVICE, s);
1470 }
1471
1472 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001473 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 ServiceArgsData s = new ServiceArgsData();
1475 s.token = token;
1476 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001477 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 s.args = args;
1479
1480 queueOrSendMessage(H.SERVICE_ARGS, s);
1481 }
1482
1483 public final void scheduleStopService(IBinder token) {
1484 queueOrSendMessage(H.STOP_SERVICE, token);
1485 }
1486
1487 public final void bindApplication(String processName,
1488 ApplicationInfo appInfo, List<ProviderInfo> providers,
1489 ComponentName instrumentationName, String profileFile,
1490 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -07001491 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493
1494 if (services != null) {
1495 // Setup the service cache in the ServiceManager
1496 ServiceManager.initServiceCache(services);
1497 }
1498
1499 AppBindData data = new AppBindData();
1500 data.processName = processName;
1501 data.appInfo = appInfo;
1502 data.providers = providers;
1503 data.instrumentationName = instrumentationName;
1504 data.profileFile = profileFile;
1505 data.instrumentationArgs = instrumentationArgs;
1506 data.instrumentationWatcher = instrumentationWatcher;
1507 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001508 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 data.config = config;
1510 queueOrSendMessage(H.BIND_APPLICATION, data);
1511 }
1512
1513 public final void scheduleExit() {
1514 queueOrSendMessage(H.EXIT_APPLICATION, null);
1515 }
1516
Christopher Tate5e1ab332009-09-01 20:32:49 -07001517 public final void scheduleSuicide() {
1518 queueOrSendMessage(H.SUICIDE, null);
1519 }
1520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 public void requestThumbnail(IBinder token) {
1522 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
1523 }
1524
1525 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001526 synchronized (mPackages) {
1527 if (mPendingConfiguration == null ||
1528 mPendingConfiguration.isOtherSeqNewer(config)) {
1529 mPendingConfiguration = config;
1530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
1532 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
1533 }
1534
1535 public void updateTimeZone() {
1536 TimeZone.setDefault(null);
1537 }
1538
1539 public void processInBackground() {
1540 mH.removeMessages(H.GC_WHEN_IDLE);
1541 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1542 }
1543
1544 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
1545 DumpServiceInfo data = new DumpServiceInfo();
1546 data.fd = fd;
1547 data.service = servicetoken;
1548 data.args = args;
1549 data.dumped = false;
1550 queueOrSendMessage(H.DUMP_SERVICE, data);
1551 synchronized (data) {
1552 while (!data.dumped) {
1553 try {
1554 data.wait();
1555 } catch (InterruptedException e) {
1556 // no need to do anything here, we will keep waiting until
1557 // dumped is set
1558 }
1559 }
1560 }
1561 }
1562
1563 // This function exists to make sure all receiver dispatching is
1564 // correctly ordered, since these are one-way calls and the binder driver
1565 // applies transaction ordering per object for such calls.
1566 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001567 int resultCode, String dataStr, Bundle extras, boolean ordered,
1568 boolean sticky) throws RemoteException {
1569 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
Bob Leee5408332009-09-04 18:31:17 -07001571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 public void scheduleLowMemory() {
1573 queueOrSendMessage(H.LOW_MEMORY, null);
1574 }
1575
1576 public void scheduleActivityConfigurationChanged(IBinder token) {
1577 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
1578 }
1579
1580 public void requestPss() {
1581 try {
1582 ActivityManagerNative.getDefault().reportPss(this,
1583 (int)Process.getPss(Process.myPid()));
1584 } catch (RemoteException e) {
1585 }
1586 }
Bob Leee5408332009-09-04 18:31:17 -07001587
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001588 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
1589 ProfilerControlData pcd = new ProfilerControlData();
1590 pcd.path = path;
1591 pcd.fd = fd;
1592 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001593 }
1594
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001595 public void setSchedulingGroup(int group) {
1596 // Note: do this immediately, since going into the foreground
1597 // should happen regardless of what pending work we have to do
1598 // and the activity manager will wait for us to report back that
1599 // we are done before sending us to the background.
1600 try {
1601 Process.setProcessGroup(Process.myPid(), group);
1602 } catch (Exception e) {
1603 Log.w(TAG, "Failed setting process group to " + group, e);
1604 }
1605 }
Bob Leee5408332009-09-04 18:31:17 -07001606
Dianne Hackborn3025ef32009-08-31 21:31:47 -07001607 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
1608 Debug.getMemoryInfo(outInfo);
1609 }
Bob Leee5408332009-09-04 18:31:17 -07001610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 @Override
1612 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1613 long nativeMax = Debug.getNativeHeapSize() / 1024;
1614 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1615 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1616
1617 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
1618 Debug.getMemoryInfo(memInfo);
1619
1620 final int nativeShared = memInfo.nativeSharedDirty;
1621 final int dalvikShared = memInfo.dalvikSharedDirty;
1622 final int otherShared = memInfo.otherSharedDirty;
1623
1624 final int nativePrivate = memInfo.nativePrivateDirty;
1625 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
1626 final int otherPrivate = memInfo.otherPrivateDirty;
1627
1628 Runtime runtime = Runtime.getRuntime();
1629
1630 long dalvikMax = runtime.totalMemory() / 1024;
1631 long dalvikFree = runtime.freeMemory() / 1024;
1632 long dalvikAllocated = dalvikMax - dalvikFree;
1633 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1634 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Dianne Hackborn21556372010-02-04 16:34:40 -08001635 long appContextInstanceCount = ContextImpl.getInstanceCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 long activityInstanceCount = Activity.getInstanceCount();
1637 int globalAssetCount = AssetManager.getGlobalAssetCount();
1638 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1639 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1640 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1641 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1642 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
1643 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
1644 SQLiteDebug.PagerStats stats = new SQLiteDebug.PagerStats();
1645 SQLiteDebug.getPagerStats(stats);
Bob Leee5408332009-09-04 18:31:17 -07001646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 // Check to see if we were called by checkin server. If so, print terse format.
1648 boolean doCheckinFormat = false;
1649 if (args != null) {
1650 for (String arg : args) {
1651 if ("-c".equals(arg)) doCheckinFormat = true;
1652 }
1653 }
Bob Leee5408332009-09-04 18:31:17 -07001654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 // For checkin, we print one long comma-separated list of values
1656 if (doCheckinFormat) {
1657 // NOTE: if you change anything significant below, also consider changing
1658 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -07001659 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -07001661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 // Header
1663 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
1664 pw.print(Process.myPid()); pw.print(',');
1665 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 // Heap info - max
1668 pw.print(nativeMax); pw.print(',');
1669 pw.print(dalvikMax); pw.print(',');
1670 pw.print("N/A,");
1671 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 // Heap info - allocated
1674 pw.print(nativeAllocated); pw.print(',');
1675 pw.print(dalvikAllocated); pw.print(',');
1676 pw.print("N/A,");
1677 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 // Heap info - free
1680 pw.print(nativeFree); pw.print(',');
1681 pw.print(dalvikFree); pw.print(',');
1682 pw.print("N/A,");
1683 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 // Heap info - proportional set size
1686 pw.print(memInfo.nativePss); pw.print(',');
1687 pw.print(memInfo.dalvikPss); pw.print(',');
1688 pw.print(memInfo.otherPss); pw.print(',');
1689 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -07001692 pw.print(nativeShared); pw.print(',');
1693 pw.print(dalvikShared); pw.print(',');
1694 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -07001698 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 pw.print(dalvikPrivate); pw.print(',');
1700 pw.print(otherPrivate); pw.print(',');
1701 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 // Object counts
1704 pw.print(viewInstanceCount); pw.print(',');
1705 pw.print(viewRootInstanceCount); pw.print(',');
1706 pw.print(appContextInstanceCount); pw.print(',');
1707 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 pw.print(globalAssetCount); pw.print(',');
1710 pw.print(globalAssetManagerCount); pw.print(',');
1711 pw.print(binderLocalObjectCount); pw.print(',');
1712 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 pw.print(binderDeathObjectCount); pw.print(',');
1715 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 // SQL
1718 pw.print(sqliteAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001719 pw.print(stats.databaseBytes / 1024); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 pw.print(stats.numPagers); pw.print(',');
1721 pw.print((stats.totalBytes - stats.referencedBytes) / 1024); pw.print(',');
1722 pw.print(stats.referencedBytes / 1024); pw.print('\n');
Bob Leee5408332009-09-04 18:31:17 -07001723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 return;
1725 }
Bob Leee5408332009-09-04 18:31:17 -07001726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 // otherwise, show human-readable format
1728 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
1729 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
1730 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
1731 nativeAllocated + dalvikAllocated);
1732 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
1733 nativeFree + dalvikFree);
1734
1735 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
1736 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
1737
1738 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
1739 nativeShared + dalvikShared + otherShared);
1740 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
1741 nativePrivate + dalvikPrivate + otherPrivate);
1742
1743 pw.println(" ");
1744 pw.println(" Objects");
1745 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
1746 viewRootInstanceCount);
1747
1748 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1749 "Activities:", activityInstanceCount);
1750
1751 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1752 "AssetManagers:", globalAssetManagerCount);
1753
1754 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1755 "Proxy Binders:", binderProxyObjectCount);
1756 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1757
1758 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 // SQLite mem info
1761 pw.println(" ");
1762 pw.println(" SQL");
1763 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "dbFiles:",
1764 stats.databaseBytes / 1024);
1765 printRow(pw, TWO_COUNT_COLUMNS, "numPagers:", stats.numPagers, "inactivePageKB:",
1766 (stats.totalBytes - stats.referencedBytes) / 1024);
1767 printRow(pw, ONE_COUNT_COLUMN, "activePageKB:", stats.referencedBytes / 1024);
Bob Leee5408332009-09-04 18:31:17 -07001768
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001769 // Asset details.
1770 String assetAlloc = AssetManager.getAssetAllocations();
1771 if (assetAlloc != null) {
1772 pw.println(" ");
1773 pw.println(" Asset Allocations");
1774 pw.print(assetAlloc);
1775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 }
1777
1778 private void printRow(PrintWriter pw, String format, Object...objs) {
1779 pw.println(String.format(format, objs));
1780 }
1781 }
1782
1783 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -07001784 private H() {
1785 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
1786 }
1787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 public static final int LAUNCH_ACTIVITY = 100;
1789 public static final int PAUSE_ACTIVITY = 101;
1790 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1791 public static final int STOP_ACTIVITY_SHOW = 103;
1792 public static final int STOP_ACTIVITY_HIDE = 104;
1793 public static final int SHOW_WINDOW = 105;
1794 public static final int HIDE_WINDOW = 106;
1795 public static final int RESUME_ACTIVITY = 107;
1796 public static final int SEND_RESULT = 108;
1797 public static final int DESTROY_ACTIVITY = 109;
1798 public static final int BIND_APPLICATION = 110;
1799 public static final int EXIT_APPLICATION = 111;
1800 public static final int NEW_INTENT = 112;
1801 public static final int RECEIVER = 113;
1802 public static final int CREATE_SERVICE = 114;
1803 public static final int SERVICE_ARGS = 115;
1804 public static final int STOP_SERVICE = 116;
1805 public static final int REQUEST_THUMBNAIL = 117;
1806 public static final int CONFIGURATION_CHANGED = 118;
1807 public static final int CLEAN_UP_CONTEXT = 119;
1808 public static final int GC_WHEN_IDLE = 120;
1809 public static final int BIND_SERVICE = 121;
1810 public static final int UNBIND_SERVICE = 122;
1811 public static final int DUMP_SERVICE = 123;
1812 public static final int LOW_MEMORY = 124;
1813 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1814 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001815 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001816 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001817 public static final int DESTROY_BACKUP_AGENT = 129;
1818 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001819 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001820 public static final int ENABLE_JIT = 132;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 String codeToString(int code) {
1822 if (localLOGV) {
1823 switch (code) {
1824 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1825 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1826 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1827 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1828 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1829 case SHOW_WINDOW: return "SHOW_WINDOW";
1830 case HIDE_WINDOW: return "HIDE_WINDOW";
1831 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1832 case SEND_RESULT: return "SEND_RESULT";
1833 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1834 case BIND_APPLICATION: return "BIND_APPLICATION";
1835 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1836 case NEW_INTENT: return "NEW_INTENT";
1837 case RECEIVER: return "RECEIVER";
1838 case CREATE_SERVICE: return "CREATE_SERVICE";
1839 case SERVICE_ARGS: return "SERVICE_ARGS";
1840 case STOP_SERVICE: return "STOP_SERVICE";
1841 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1842 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1843 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1844 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1845 case BIND_SERVICE: return "BIND_SERVICE";
1846 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1847 case DUMP_SERVICE: return "DUMP_SERVICE";
1848 case LOW_MEMORY: return "LOW_MEMORY";
1849 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1850 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001851 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001852 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1853 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001854 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001855 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001856 case ENABLE_JIT: return "ENABLE_JIT";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 }
1858 }
1859 return "(unknown)";
1860 }
1861 public void handleMessage(Message msg) {
1862 switch (msg.what) {
1863 case LAUNCH_ACTIVITY: {
1864 ActivityRecord r = (ActivityRecord)msg.obj;
1865
1866 r.packageInfo = getPackageInfoNoCheck(
1867 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001868 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 } break;
1870 case RELAUNCH_ACTIVITY: {
1871 ActivityRecord r = (ActivityRecord)msg.obj;
1872 handleRelaunchActivity(r, msg.arg1);
1873 } break;
1874 case PAUSE_ACTIVITY:
1875 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001876 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 break;
1878 case PAUSE_ACTIVITY_FINISHING:
1879 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1880 break;
1881 case STOP_ACTIVITY_SHOW:
1882 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1883 break;
1884 case STOP_ACTIVITY_HIDE:
1885 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1886 break;
1887 case SHOW_WINDOW:
1888 handleWindowVisibility((IBinder)msg.obj, true);
1889 break;
1890 case HIDE_WINDOW:
1891 handleWindowVisibility((IBinder)msg.obj, false);
1892 break;
1893 case RESUME_ACTIVITY:
1894 handleResumeActivity((IBinder)msg.obj, true,
1895 msg.arg1 != 0);
1896 break;
1897 case SEND_RESULT:
1898 handleSendResult((ResultData)msg.obj);
1899 break;
1900 case DESTROY_ACTIVITY:
1901 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1902 msg.arg2, false);
1903 break;
1904 case BIND_APPLICATION:
1905 AppBindData data = (AppBindData)msg.obj;
1906 handleBindApplication(data);
1907 break;
1908 case EXIT_APPLICATION:
1909 if (mInitialApplication != null) {
1910 mInitialApplication.onTerminate();
1911 }
1912 Looper.myLooper().quit();
1913 break;
1914 case NEW_INTENT:
1915 handleNewIntent((NewIntentData)msg.obj);
1916 break;
1917 case RECEIVER:
1918 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001919 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 break;
1921 case CREATE_SERVICE:
1922 handleCreateService((CreateServiceData)msg.obj);
1923 break;
1924 case BIND_SERVICE:
1925 handleBindService((BindServiceData)msg.obj);
1926 break;
1927 case UNBIND_SERVICE:
1928 handleUnbindService((BindServiceData)msg.obj);
1929 break;
1930 case SERVICE_ARGS:
1931 handleServiceArgs((ServiceArgsData)msg.obj);
1932 break;
1933 case STOP_SERVICE:
1934 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001935 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 break;
1937 case REQUEST_THUMBNAIL:
1938 handleRequestThumbnail((IBinder)msg.obj);
1939 break;
1940 case CONFIGURATION_CHANGED:
1941 handleConfigurationChanged((Configuration)msg.obj);
1942 break;
1943 case CLEAN_UP_CONTEXT:
1944 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1945 cci.context.performFinalCleanup(cci.who, cci.what);
1946 break;
1947 case GC_WHEN_IDLE:
1948 scheduleGcIdler();
1949 break;
1950 case DUMP_SERVICE:
1951 handleDumpService((DumpServiceInfo)msg.obj);
1952 break;
1953 case LOW_MEMORY:
1954 handleLowMemory();
1955 break;
1956 case ACTIVITY_CONFIGURATION_CHANGED:
1957 handleActivityConfigurationChanged((IBinder)msg.obj);
1958 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001959 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001960 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001961 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001962 case CREATE_BACKUP_AGENT:
1963 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1964 break;
1965 case DESTROY_BACKUP_AGENT:
1966 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1967 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001968 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001969 Process.killProcess(Process.myPid());
1970 break;
1971 case REMOVE_PROVIDER:
1972 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001973 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001974 case ENABLE_JIT:
1975 ensureJitEnabled();
1976 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
1978 }
Bob Leee5408332009-09-04 18:31:17 -07001979
1980 void maybeSnapshot() {
1981 if (mBoundApplication != null) {
1982 SamplingProfilerIntegration.writeSnapshot(
1983 mBoundApplication.processName);
1984 }
1985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987
1988 private final class Idler implements MessageQueue.IdleHandler {
1989 public final boolean queueIdle() {
1990 ActivityRecord a = mNewActivities;
1991 if (a != null) {
1992 mNewActivities = null;
1993 IActivityManager am = ActivityManagerNative.getDefault();
1994 ActivityRecord prev;
1995 do {
1996 if (localLOGV) Log.v(
1997 TAG, "Reporting idle of " + a +
1998 " finished=" +
1999 (a.activity != null ? a.activity.mFinished : false));
2000 if (a.activity != null && !a.activity.mFinished) {
2001 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07002002 am.activityIdle(a.token, a.createdConfig);
2003 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 } catch (RemoteException ex) {
2005 }
2006 }
2007 prev = a;
2008 a = a.nextIdle;
2009 prev.nextIdle = null;
2010 } while (a != null);
2011 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002012 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 return false;
2014 }
2015 }
2016
2017 final class GcIdler implements MessageQueue.IdleHandler {
2018 public final boolean queueIdle() {
2019 doGcIfNeeded();
2020 return false;
2021 }
2022 }
2023
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002024 private final static class ResourcesKey {
2025 final private String mResDir;
2026 final private float mScale;
2027 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07002028
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002029 ResourcesKey(String resDir, float scale) {
2030 mResDir = resDir;
2031 mScale = scale;
2032 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
2033 }
Bob Leee5408332009-09-04 18:31:17 -07002034
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002035 @Override
2036 public int hashCode() {
2037 return mHash;
2038 }
2039
2040 @Override
2041 public boolean equals(Object obj) {
2042 if (!(obj instanceof ResourcesKey)) {
2043 return false;
2044 }
2045 ResourcesKey peer = (ResourcesKey) obj;
2046 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
2047 }
2048 }
2049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 static IPackageManager sPackageManager;
2051
2052 final ApplicationThread mAppThread = new ApplicationThread();
2053 final Looper mLooper = Looper.myLooper();
2054 final H mH = new H();
2055 final HashMap<IBinder, ActivityRecord> mActivities
2056 = new HashMap<IBinder, ActivityRecord>();
2057 // List of new activities (via ActivityRecord.nextIdle) that should
2058 // be reported when next we idle.
2059 ActivityRecord mNewActivities = null;
2060 // Number of activities that are currently visible on-screen.
2061 int mNumVisibleActivities = 0;
2062 final HashMap<IBinder, Service> mServices
2063 = new HashMap<IBinder, Service>();
2064 AppBindData mBoundApplication;
2065 Configuration mConfiguration;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002066 Configuration mResConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 Application mInitialApplication;
2068 final ArrayList<Application> mAllApplications
2069 = new ArrayList<Application>();
Christopher Tate181fafa2009-05-14 11:12:14 -07002070 // set of instantiated backup agents, keyed by package name
2071 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 static final ThreadLocal sThreadLocal = new ThreadLocal();
2073 Instrumentation mInstrumentation;
2074 String mInstrumentationAppDir = null;
2075 String mInstrumentationAppPackage = null;
2076 String mInstrumentedAppDir = null;
2077 boolean mSystemThread = false;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002078 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 // These can be accessed by multiple threads; mPackages is the lock.
2081 // XXX For now we keep around information about all packages we have
2082 // seen, not removing entries from this map.
2083 final HashMap<String, WeakReference<PackageInfo>> mPackages
2084 = new HashMap<String, WeakReference<PackageInfo>>();
2085 final HashMap<String, WeakReference<PackageInfo>> mResourcePackages
2086 = new HashMap<String, WeakReference<PackageInfo>>();
2087 Display mDisplay = null;
2088 DisplayMetrics mDisplayMetrics = null;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002089 HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
2090 = new HashMap<ResourcesKey, WeakReference<Resources> >();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002091 final ArrayList<ActivityRecord> mRelaunchingActivities
2092 = new ArrayList<ActivityRecord>();
2093 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094
2095 // The lock of mProviderMap protects the following variables.
2096 final HashMap<String, ProviderRecord> mProviderMap
2097 = new HashMap<String, ProviderRecord>();
2098 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
2099 = new HashMap<IBinder, ProviderRefCount>();
2100 final HashMap<IBinder, ProviderRecord> mLocalProviders
2101 = new HashMap<IBinder, ProviderRecord>();
2102
2103 final GcIdler mGcIdler = new GcIdler();
2104 boolean mGcIdlerScheduled = false;
2105
2106 public final PackageInfo getPackageInfo(String packageName, int flags) {
2107 synchronized (mPackages) {
2108 WeakReference<PackageInfo> ref;
2109 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
2110 ref = mPackages.get(packageName);
2111 } else {
2112 ref = mResourcePackages.get(packageName);
2113 }
2114 PackageInfo packageInfo = ref != null ? ref.get() : null;
2115 //Log.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
2116 if (packageInfo != null && (packageInfo.mResources == null
2117 || packageInfo.mResources.getAssets().isUpToDate())) {
2118 if (packageInfo.isSecurityViolation()
2119 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2120 throw new SecurityException(
2121 "Requesting code from " + packageName
2122 + " to be run in process "
2123 + mBoundApplication.processName
2124 + "/" + mBoundApplication.appInfo.uid);
2125 }
2126 return packageInfo;
2127 }
2128 }
2129
2130 ApplicationInfo ai = null;
2131 try {
2132 ai = getPackageManager().getApplicationInfo(packageName,
2133 PackageManager.GET_SHARED_LIBRARY_FILES);
2134 } catch (RemoteException e) {
2135 }
2136
2137 if (ai != null) {
2138 return getPackageInfo(ai, flags);
2139 }
2140
2141 return null;
2142 }
2143
2144 public final PackageInfo getPackageInfo(ApplicationInfo ai, int flags) {
2145 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2146 boolean securityViolation = includeCode && ai.uid != 0
2147 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
2148 ? ai.uid != mBoundApplication.appInfo.uid : true);
2149 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2150 |Context.CONTEXT_IGNORE_SECURITY))
2151 == Context.CONTEXT_INCLUDE_CODE) {
2152 if (securityViolation) {
2153 String msg = "Requesting code from " + ai.packageName
2154 + " (with uid " + ai.uid + ")";
2155 if (mBoundApplication != null) {
2156 msg = msg + " to be run in process "
2157 + mBoundApplication.processName + " (with uid "
2158 + mBoundApplication.appInfo.uid + ")";
2159 }
2160 throw new SecurityException(msg);
2161 }
2162 }
2163 return getPackageInfo(ai, null, securityViolation, includeCode);
2164 }
2165
2166 public final PackageInfo getPackageInfoNoCheck(ApplicationInfo ai) {
2167 return getPackageInfo(ai, null, false, true);
2168 }
2169
2170 private final PackageInfo getPackageInfo(ApplicationInfo aInfo,
2171 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
2172 synchronized (mPackages) {
2173 WeakReference<PackageInfo> ref;
2174 if (includeCode) {
2175 ref = mPackages.get(aInfo.packageName);
2176 } else {
2177 ref = mResourcePackages.get(aInfo.packageName);
2178 }
2179 PackageInfo packageInfo = ref != null ? ref.get() : null;
2180 if (packageInfo == null || (packageInfo.mResources != null
2181 && !packageInfo.mResources.getAssets().isUpToDate())) {
2182 if (localLOGV) Log.v(TAG, (includeCode ? "Loading code package "
2183 : "Loading resource-only package ") + aInfo.packageName
2184 + " (in " + (mBoundApplication != null
2185 ? mBoundApplication.processName : null)
2186 + ")");
2187 packageInfo =
2188 new PackageInfo(this, aInfo, this, baseLoader,
2189 securityViolation, includeCode &&
2190 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
2191 if (includeCode) {
2192 mPackages.put(aInfo.packageName,
2193 new WeakReference<PackageInfo>(packageInfo));
2194 } else {
2195 mResourcePackages.put(aInfo.packageName,
2196 new WeakReference<PackageInfo>(packageInfo));
2197 }
2198 }
2199 return packageInfo;
2200 }
2201 }
2202
2203 public final boolean hasPackageInfo(String packageName) {
2204 synchronized (mPackages) {
2205 WeakReference<PackageInfo> ref;
2206 ref = mPackages.get(packageName);
2207 if (ref != null && ref.get() != null) {
2208 return true;
2209 }
2210 ref = mResourcePackages.get(packageName);
2211 if (ref != null && ref.get() != null) {
2212 return true;
2213 }
2214 return false;
2215 }
2216 }
Bob Leee5408332009-09-04 18:31:17 -07002217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 ActivityThread() {
2219 }
2220
2221 public ApplicationThread getApplicationThread()
2222 {
2223 return mAppThread;
2224 }
2225
2226 public Instrumentation getInstrumentation()
2227 {
2228 return mInstrumentation;
2229 }
2230
2231 public Configuration getConfiguration() {
2232 return mConfiguration;
2233 }
2234
2235 public boolean isProfiling() {
2236 return mBoundApplication != null && mBoundApplication.profileFile != null;
2237 }
2238
2239 public String getProfileFilePath() {
2240 return mBoundApplication.profileFile;
2241 }
2242
2243 public Looper getLooper() {
2244 return mLooper;
2245 }
2246
2247 public Application getApplication() {
2248 return mInitialApplication;
2249 }
Bob Leee5408332009-09-04 18:31:17 -07002250
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002251 public String getProcessName() {
2252 return mBoundApplication.processName;
2253 }
Bob Leee5408332009-09-04 18:31:17 -07002254
Dianne Hackborn21556372010-02-04 16:34:40 -08002255 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 synchronized (this) {
2257 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08002258 ContextImpl context =
2259 ContextImpl.createSystemContext(this);
Mike Cleron432b7132009-09-24 15:28:29 -07002260 PackageInfo info = new PackageInfo(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 context.init(info, null, this);
2262 context.getResources().updateConfiguration(
2263 getConfiguration(), getDisplayMetricsLocked(false));
2264 mSystemContext = context;
2265 //Log.i(TAG, "Created system resources " + context.getResources()
2266 // + ": " + context.getResources().getConfiguration());
2267 }
2268 }
2269 return mSystemContext;
2270 }
2271
Mike Cleron432b7132009-09-24 15:28:29 -07002272 public void installSystemApplicationInfo(ApplicationInfo info) {
2273 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08002274 ContextImpl context = getSystemContext();
Mike Cleron432b7132009-09-24 15:28:29 -07002275 context.init(new PackageInfo(this, "android", context, info), null, this);
2276 }
2277 }
2278
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002279 void ensureJitEnabled() {
2280 if (!mJitEnabled) {
2281 mJitEnabled = true;
2282 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
2283 }
2284 }
2285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 void scheduleGcIdler() {
2287 if (!mGcIdlerScheduled) {
2288 mGcIdlerScheduled = true;
2289 Looper.myQueue().addIdleHandler(mGcIdler);
2290 }
2291 mH.removeMessages(H.GC_WHEN_IDLE);
2292 }
2293
2294 void unscheduleGcIdler() {
2295 if (mGcIdlerScheduled) {
2296 mGcIdlerScheduled = false;
2297 Looper.myQueue().removeIdleHandler(mGcIdler);
2298 }
2299 mH.removeMessages(H.GC_WHEN_IDLE);
2300 }
2301
2302 void doGcIfNeeded() {
2303 mGcIdlerScheduled = false;
2304 final long now = SystemClock.uptimeMillis();
2305 //Log.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
2306 // + "m now=" + now);
2307 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
2308 //Log.i(TAG, "**** WE DO, WE DO WANT TO GC!");
2309 BinderInternal.forceGc("bg");
2310 }
2311 }
2312
2313 public final ActivityInfo resolveActivityInfo(Intent intent) {
2314 ActivityInfo aInfo = intent.resolveActivityInfo(
2315 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2316 if (aInfo == null) {
2317 // Throw an exception.
2318 Instrumentation.checkStartActivityResult(
2319 IActivityManager.START_CLASS_NOT_FOUND, intent);
2320 }
2321 return aInfo;
2322 }
Bob Leee5408332009-09-04 18:31:17 -07002323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
2326 Object lastNonConfigurationInstance) {
2327 ActivityRecord r = new ActivityRecord();
2328 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002329 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 r.intent = intent;
2331 r.state = state;
2332 r.parent = parent;
2333 r.embeddedID = id;
2334 r.activityInfo = activityInfo;
2335 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
2336 if (localLOGV) {
2337 ComponentName compname = intent.getComponent();
2338 String name;
2339 if (compname != null) {
2340 name = compname.toShortString();
2341 } else {
2342 name = "(Intent " + intent + ").getComponent() returned null";
2343 }
2344 Log.v(TAG, "Performing launch: action=" + intent.getAction()
2345 + ", comp=" + name
2346 + ", token=" + token);
2347 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07002348 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 }
2350
2351 public final Activity getActivity(IBinder token) {
2352 return mActivities.get(token).activity;
2353 }
2354
2355 public final void sendActivityResult(
2356 IBinder token, String id, int requestCode,
2357 int resultCode, Intent data) {
Chris Tate8a7dc172009-03-24 20:11:42 -07002358 if (DEBUG_RESULTS) Log.v(TAG, "sendActivityResult: id=" + id
2359 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2361 list.add(new ResultInfo(id, requestCode, resultCode, data));
2362 mAppThread.scheduleSendResult(token, list);
2363 }
2364
2365 // if the thread hasn't started yet, we don't have the handler, so just
2366 // save the messages until we're ready.
2367 private final void queueOrSendMessage(int what, Object obj) {
2368 queueOrSendMessage(what, obj, 0, 0);
2369 }
2370
2371 private final void queueOrSendMessage(int what, Object obj, int arg1) {
2372 queueOrSendMessage(what, obj, arg1, 0);
2373 }
2374
2375 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
2376 synchronized (this) {
2377 if (localLOGV) Log.v(
2378 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2379 + ": " + arg1 + " / " + obj);
2380 Message msg = Message.obtain();
2381 msg.what = what;
2382 msg.obj = obj;
2383 msg.arg1 = arg1;
2384 msg.arg2 = arg2;
2385 mH.sendMessage(msg);
2386 }
2387 }
2388
Dianne Hackborn21556372010-02-04 16:34:40 -08002389 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 String what) {
2391 ContextCleanupInfo cci = new ContextCleanupInfo();
2392 cci.context = context;
2393 cci.who = who;
2394 cci.what = what;
2395 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
2396 }
2397
Christopher Tateb70f3df2009-04-07 16:07:59 -07002398 private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
2400
2401 ActivityInfo aInfo = r.activityInfo;
2402 if (r.packageInfo == null) {
2403 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
2404 Context.CONTEXT_INCLUDE_CODE);
2405 }
Bob Leee5408332009-09-04 18:31:17 -07002406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 ComponentName component = r.intent.getComponent();
2408 if (component == null) {
2409 component = r.intent.resolveActivity(
2410 mInitialApplication.getPackageManager());
2411 r.intent.setComponent(component);
2412 }
2413
2414 if (r.activityInfo.targetActivity != null) {
2415 component = new ComponentName(r.activityInfo.packageName,
2416 r.activityInfo.targetActivity);
2417 }
2418
2419 Activity activity = null;
2420 try {
2421 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
2422 activity = mInstrumentation.newActivity(
2423 cl, component.getClassName(), r.intent);
2424 r.intent.setExtrasClassLoader(cl);
2425 if (r.state != null) {
2426 r.state.setClassLoader(cl);
2427 }
2428 } catch (Exception e) {
2429 if (!mInstrumentation.onException(activity, e)) {
2430 throw new RuntimeException(
2431 "Unable to instantiate activity " + component
2432 + ": " + e.toString(), e);
2433 }
2434 }
2435
2436 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002437 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 if (localLOGV) Log.v(TAG, "Performing launch of " + r);
2440 if (localLOGV) Log.v(
2441 TAG, r + ": app=" + app
2442 + ", appName=" + app.getPackageName()
2443 + ", pkg=" + r.packageInfo.getPackageName()
2444 + ", comp=" + r.intent.getComponent().toShortString()
2445 + ", dir=" + r.packageInfo.getAppDir());
2446
2447 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08002448 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 appContext.init(r.packageInfo, r.token, this);
2450 appContext.setOuterContext(activity);
2451 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
2452 Configuration config = new Configuration(mConfiguration);
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002453 if (DEBUG_CONFIGURATION) Log.v(TAG, "Launching activity "
2454 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002455 activity.attach(appContext, this, getInstrumentation(), r.token,
2456 r.ident, app, r.intent, r.activityInfo, title, r.parent,
2457 r.embeddedID, r.lastNonConfigurationInstance,
2458 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07002459
Christopher Tateb70f3df2009-04-07 16:07:59 -07002460 if (customIntent != null) {
2461 activity.mIntent = customIntent;
2462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 r.lastNonConfigurationInstance = null;
2464 r.lastNonConfigurationChildInstances = null;
2465 activity.mStartedActivity = false;
2466 int theme = r.activityInfo.getThemeResource();
2467 if (theme != 0) {
2468 activity.setTheme(theme);
2469 }
2470
2471 activity.mCalled = false;
2472 mInstrumentation.callActivityOnCreate(activity, r.state);
2473 if (!activity.mCalled) {
2474 throw new SuperNotCalledException(
2475 "Activity " + r.intent.getComponent().toShortString() +
2476 " did not call through to super.onCreate()");
2477 }
2478 r.activity = activity;
2479 r.stopped = true;
2480 if (!r.activity.mFinished) {
2481 activity.performStart();
2482 r.stopped = false;
2483 }
2484 if (!r.activity.mFinished) {
2485 if (r.state != null) {
2486 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2487 }
2488 }
2489 if (!r.activity.mFinished) {
2490 activity.mCalled = false;
2491 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2492 if (!activity.mCalled) {
2493 throw new SuperNotCalledException(
2494 "Activity " + r.intent.getComponent().toShortString() +
2495 " did not call through to super.onPostCreate()");
2496 }
2497 }
2498 r.state = null;
2499 }
2500 r.paused = true;
2501
2502 mActivities.put(r.token, r);
2503
2504 } catch (SuperNotCalledException e) {
2505 throw e;
2506
2507 } catch (Exception e) {
2508 if (!mInstrumentation.onException(activity, e)) {
2509 throw new RuntimeException(
2510 "Unable to start activity " + component
2511 + ": " + e.toString(), e);
2512 }
2513 }
2514
2515 return activity;
2516 }
2517
Christopher Tateb70f3df2009-04-07 16:07:59 -07002518 private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 // If we are getting ready to gc after going to the background, well
2520 // we are back active so skip it.
2521 unscheduleGcIdler();
2522
2523 if (localLOGV) Log.v(
2524 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002525 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526
2527 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002528 r.createdConfig = new Configuration(mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 handleResumeActivity(r.token, false, r.isForward);
2530
2531 if (!r.activity.mFinished && r.startsNotResumed) {
2532 // The activity manager actually wants this one to start out
2533 // paused, because it needs to be visible but isn't in the
2534 // foreground. We accomplish this by going through the
2535 // normal startup (because activities expect to go through
2536 // onResume() the first time they run, before their window
2537 // is displayed), and then pausing it. However, in this case
2538 // we do -not- need to do the full pause cycle (of freezing
2539 // and such) because the activity manager assumes it can just
2540 // retain the current state it has.
2541 try {
2542 r.activity.mCalled = false;
2543 mInstrumentation.callActivityOnPause(r.activity);
2544 if (!r.activity.mCalled) {
2545 throw new SuperNotCalledException(
2546 "Activity " + r.intent.getComponent().toShortString() +
2547 " did not call through to super.onPause()");
2548 }
2549
2550 } catch (SuperNotCalledException e) {
2551 throw e;
2552
2553 } catch (Exception e) {
2554 if (!mInstrumentation.onException(r.activity, e)) {
2555 throw new RuntimeException(
2556 "Unable to pause activity "
2557 + r.intent.getComponent().toShortString()
2558 + ": " + e.toString(), e);
2559 }
2560 }
2561 r.paused = true;
2562 }
2563 } else {
2564 // If there was an error, for any reason, tell the activity
2565 // manager to stop us.
2566 try {
2567 ActivityManagerNative.getDefault()
2568 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2569 } catch (RemoteException ex) {
2570 }
2571 }
2572 }
2573
2574 private final void deliverNewIntents(ActivityRecord r,
2575 List<Intent> intents) {
2576 final int N = intents.size();
2577 for (int i=0; i<N; i++) {
2578 Intent intent = intents.get(i);
2579 intent.setExtrasClassLoader(r.activity.getClassLoader());
2580 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2581 }
2582 }
2583
2584 public final void performNewIntents(IBinder token,
2585 List<Intent> intents) {
2586 ActivityRecord r = mActivities.get(token);
2587 if (r != null) {
2588 final boolean resumed = !r.paused;
2589 if (resumed) {
2590 mInstrumentation.callActivityOnPause(r.activity);
2591 }
2592 deliverNewIntents(r, intents);
2593 if (resumed) {
2594 mInstrumentation.callActivityOnResume(r.activity);
2595 }
2596 }
2597 }
Bob Leee5408332009-09-04 18:31:17 -07002598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 private final void handleNewIntent(NewIntentData data) {
2600 performNewIntents(data.token, data.intents);
2601 }
2602
2603 private final void handleReceiver(ReceiverData data) {
2604 // If we are getting ready to gc after going to the background, well
2605 // we are back active so skip it.
2606 unscheduleGcIdler();
2607
2608 String component = data.intent.getComponent().getClassName();
2609
2610 PackageInfo packageInfo = getPackageInfoNoCheck(
2611 data.info.applicationInfo);
2612
2613 IActivityManager mgr = ActivityManagerNative.getDefault();
2614
2615 BroadcastReceiver receiver = null;
2616 try {
2617 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2618 data.intent.setExtrasClassLoader(cl);
2619 if (data.resultExtras != null) {
2620 data.resultExtras.setClassLoader(cl);
2621 }
2622 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2623 } catch (Exception e) {
2624 try {
2625 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2626 data.resultData, data.resultExtras, data.resultAbort);
2627 } catch (RemoteException ex) {
2628 }
2629 throw new RuntimeException(
2630 "Unable to instantiate receiver " + component
2631 + ": " + e.toString(), e);
2632 }
2633
2634 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002635 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 if (localLOGV) Log.v(
2638 TAG, "Performing receive of " + data.intent
2639 + ": app=" + app
2640 + ", appName=" + app.getPackageName()
2641 + ", pkg=" + packageInfo.getPackageName()
2642 + ", comp=" + data.intent.getComponent().toShortString()
2643 + ", dir=" + packageInfo.getAppDir());
2644
Dianne Hackborn21556372010-02-04 16:34:40 -08002645 ContextImpl context = (ContextImpl)app.getBaseContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 receiver.setOrderedHint(true);
2647 receiver.setResult(data.resultCode, data.resultData,
2648 data.resultExtras);
2649 receiver.setOrderedHint(data.sync);
2650 receiver.onReceive(context.getReceiverRestrictedContext(),
2651 data.intent);
2652 } catch (Exception e) {
2653 try {
2654 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2655 data.resultData, data.resultExtras, data.resultAbort);
2656 } catch (RemoteException ex) {
2657 }
2658 if (!mInstrumentation.onException(receiver, e)) {
2659 throw new RuntimeException(
2660 "Unable to start receiver " + component
2661 + ": " + e.toString(), e);
2662 }
2663 }
2664
2665 try {
2666 if (data.sync) {
2667 mgr.finishReceiver(
2668 mAppThread.asBinder(), receiver.getResultCode(),
2669 receiver.getResultData(), receiver.getResultExtras(false),
2670 receiver.getAbortBroadcast());
2671 } else {
2672 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
2673 }
2674 } catch (RemoteException ex) {
2675 }
2676 }
2677
Christopher Tate181fafa2009-05-14 11:12:14 -07002678 // Instantiate a BackupAgent and tell it that it's alive
2679 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
2680 if (DEBUG_BACKUP) Log.v(TAG, "handleCreateBackupAgent: " + data);
2681
2682 // no longer idle; we have backup work to do
2683 unscheduleGcIdler();
2684
2685 // instantiate the BackupAgent class named in the manifest
2686 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2687 String packageName = packageInfo.mPackageName;
2688 if (mBackupAgents.get(packageName) != null) {
2689 Log.d(TAG, "BackupAgent " + " for " + packageName
2690 + " already exists");
2691 return;
2692 }
Bob Leee5408332009-09-04 18:31:17 -07002693
Christopher Tate181fafa2009-05-14 11:12:14 -07002694 BackupAgent agent = null;
2695 String classname = data.appInfo.backupAgentName;
2696 if (classname == null) {
2697 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
2698 Log.e(TAG, "Attempted incremental backup but no defined agent for "
2699 + packageName);
2700 return;
2701 }
2702 classname = "android.app.FullBackupAgent";
2703 }
2704 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002705 IBinder binder = null;
2706 try {
2707 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2708 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
2709
2710 // set up the agent's context
2711 if (DEBUG_BACKUP) Log.v(TAG, "Initializing BackupAgent "
2712 + data.appInfo.backupAgentName);
2713
Dianne Hackborn21556372010-02-04 16:34:40 -08002714 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07002715 context.init(packageInfo, null, this);
2716 context.setOuterContext(agent);
2717 agent.attach(context);
2718
2719 agent.onCreate();
2720 binder = agent.onBind();
2721 mBackupAgents.put(packageName, agent);
2722 } catch (Exception e) {
2723 // If this is during restore, fail silently; otherwise go
2724 // ahead and let the user see the crash.
2725 Log.e(TAG, "Agent threw during creation: " + e);
2726 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
2727 throw e;
2728 }
2729 // falling through with 'binder' still null
2730 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002731
2732 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002733 try {
2734 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2735 } catch (RemoteException e) {
2736 // nothing to do.
2737 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002738 } catch (Exception e) {
2739 throw new RuntimeException("Unable to create BackupAgent "
2740 + data.appInfo.backupAgentName + ": " + e.toString(), e);
2741 }
2742 }
2743
2744 // Tear down a BackupAgent
2745 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
2746 if (DEBUG_BACKUP) Log.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002747
Christopher Tate181fafa2009-05-14 11:12:14 -07002748 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2749 String packageName = packageInfo.mPackageName;
2750 BackupAgent agent = mBackupAgents.get(packageName);
2751 if (agent != null) {
2752 try {
2753 agent.onDestroy();
2754 } catch (Exception e) {
2755 Log.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
2756 e.printStackTrace();
2757 }
2758 mBackupAgents.remove(packageName);
2759 } else {
2760 Log.w(TAG, "Attempt to destroy unknown backup agent " + data);
2761 }
2762 }
2763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 private final void handleCreateService(CreateServiceData data) {
2765 // If we are getting ready to gc after going to the background, well
2766 // we are back active so skip it.
2767 unscheduleGcIdler();
2768
2769 PackageInfo packageInfo = getPackageInfoNoCheck(
2770 data.info.applicationInfo);
2771 Service service = null;
2772 try {
2773 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2774 service = (Service) cl.loadClass(data.info.name).newInstance();
2775 } catch (Exception e) {
2776 if (!mInstrumentation.onException(service, e)) {
2777 throw new RuntimeException(
2778 "Unable to instantiate service " + data.info.name
2779 + ": " + e.toString(), e);
2780 }
2781 }
2782
2783 try {
2784 if (localLOGV) Log.v(TAG, "Creating service " + data.info.name);
2785
Dianne Hackborn21556372010-02-04 16:34:40 -08002786 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 context.init(packageInfo, null, this);
2788
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002789 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 context.setOuterContext(service);
2791 service.attach(context, this, data.info.name, data.token, app,
2792 ActivityManagerNative.getDefault());
2793 service.onCreate();
2794 mServices.put(data.token, service);
2795 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002796 ActivityManagerNative.getDefault().serviceDoneExecuting(
2797 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 } catch (RemoteException e) {
2799 // nothing to do.
2800 }
2801 } catch (Exception e) {
2802 if (!mInstrumentation.onException(service, e)) {
2803 throw new RuntimeException(
2804 "Unable to create service " + data.info.name
2805 + ": " + e.toString(), e);
2806 }
2807 }
2808 }
2809
2810 private final void handleBindService(BindServiceData data) {
2811 Service s = mServices.get(data.token);
2812 if (s != null) {
2813 try {
2814 data.intent.setExtrasClassLoader(s.getClassLoader());
2815 try {
2816 if (!data.rebind) {
2817 IBinder binder = s.onBind(data.intent);
2818 ActivityManagerNative.getDefault().publishService(
2819 data.token, data.intent, binder);
2820 } else {
2821 s.onRebind(data.intent);
2822 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002823 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002825 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 } catch (RemoteException ex) {
2827 }
2828 } catch (Exception e) {
2829 if (!mInstrumentation.onException(s, e)) {
2830 throw new RuntimeException(
2831 "Unable to bind to service " + s
2832 + " with " + data.intent + ": " + e.toString(), e);
2833 }
2834 }
2835 }
2836 }
2837
2838 private final void handleUnbindService(BindServiceData data) {
2839 Service s = mServices.get(data.token);
2840 if (s != null) {
2841 try {
2842 data.intent.setExtrasClassLoader(s.getClassLoader());
2843 boolean doRebind = s.onUnbind(data.intent);
2844 try {
2845 if (doRebind) {
2846 ActivityManagerNative.getDefault().unbindFinished(
2847 data.token, data.intent, doRebind);
2848 } else {
2849 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002850 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 }
2852 } catch (RemoteException ex) {
2853 }
2854 } catch (Exception e) {
2855 if (!mInstrumentation.onException(s, e)) {
2856 throw new RuntimeException(
2857 "Unable to unbind to service " + s
2858 + " with " + data.intent + ": " + e.toString(), e);
2859 }
2860 }
2861 }
2862 }
2863
2864 private void handleDumpService(DumpServiceInfo info) {
2865 try {
2866 Service s = mServices.get(info.service);
2867 if (s != null) {
2868 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2869 s.dump(info.fd, pw, info.args);
2870 pw.close();
2871 }
2872 } finally {
2873 synchronized (info) {
2874 info.dumped = true;
2875 info.notifyAll();
2876 }
2877 }
2878 }
2879
2880 private final void handleServiceArgs(ServiceArgsData data) {
2881 Service s = mServices.get(data.token);
2882 if (s != null) {
2883 try {
2884 if (data.args != null) {
2885 data.args.setExtrasClassLoader(s.getClassLoader());
2886 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002887 int res = s.onStartCommand(data.args, data.flags, data.startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002889 ActivityManagerNative.getDefault().serviceDoneExecuting(
2890 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 } catch (RemoteException e) {
2892 // nothing to do.
2893 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002894 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 } catch (Exception e) {
2896 if (!mInstrumentation.onException(s, e)) {
2897 throw new RuntimeException(
2898 "Unable to start service " + s
2899 + " with " + data.args + ": " + e.toString(), e);
2900 }
2901 }
2902 }
2903 }
2904
2905 private final void handleStopService(IBinder token) {
2906 Service s = mServices.remove(token);
2907 if (s != null) {
2908 try {
2909 if (localLOGV) Log.v(TAG, "Destroying service " + s);
2910 s.onDestroy();
2911 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002912 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002914 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 }
2916 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002917 ActivityManagerNative.getDefault().serviceDoneExecuting(
2918 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 } catch (RemoteException e) {
2920 // nothing to do.
2921 }
2922 } catch (Exception e) {
2923 if (!mInstrumentation.onException(s, e)) {
2924 throw new RuntimeException(
2925 "Unable to stop service " + s
2926 + ": " + e.toString(), e);
2927 }
2928 }
2929 }
2930 //Log.i(TAG, "Running services: " + mServices);
2931 }
2932
2933 public final ActivityRecord performResumeActivity(IBinder token,
2934 boolean clearHide) {
2935 ActivityRecord r = mActivities.get(token);
2936 if (localLOGV) Log.v(TAG, "Performing resume of " + r
2937 + " finished=" + r.activity.mFinished);
2938 if (r != null && !r.activity.mFinished) {
2939 if (clearHide) {
2940 r.hideForNow = false;
2941 r.activity.mStartedActivity = false;
2942 }
2943 try {
2944 if (r.pendingIntents != null) {
2945 deliverNewIntents(r, r.pendingIntents);
2946 r.pendingIntents = null;
2947 }
2948 if (r.pendingResults != null) {
2949 deliverResults(r, r.pendingResults);
2950 r.pendingResults = null;
2951 }
2952 r.activity.performResume();
2953
Bob Leee5408332009-09-04 18:31:17 -07002954 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 r.paused = false;
2958 r.stopped = false;
2959 if (r.activity.mStartedActivity) {
2960 r.hideForNow = true;
2961 }
2962 r.state = null;
2963 } catch (Exception e) {
2964 if (!mInstrumentation.onException(r.activity, e)) {
2965 throw new RuntimeException(
2966 "Unable to resume activity "
2967 + r.intent.getComponent().toShortString()
2968 + ": " + e.toString(), e);
2969 }
2970 }
2971 }
2972 return r;
2973 }
2974
2975 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2976 // If we are getting ready to gc after going to the background, well
2977 // we are back active so skip it.
2978 unscheduleGcIdler();
2979
2980 ActivityRecord r = performResumeActivity(token, clearHide);
2981
2982 if (r != null) {
2983 final Activity a = r.activity;
2984
2985 if (localLOGV) Log.v(
2986 TAG, "Resume " + r + " started activity: " +
2987 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2988 + ", finished: " + a.mFinished);
2989
2990 final int forwardBit = isForward ?
2991 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 // If the window hasn't yet been added to the window manager,
2994 // and this guy didn't finish itself or start another activity,
2995 // then go ahead and add the window.
2996 if (r.window == null && !a.mFinished && !a.mStartedActivity) {
2997 r.window = r.activity.getWindow();
2998 View decor = r.window.getDecorView();
2999 decor.setVisibility(View.INVISIBLE);
3000 ViewManager wm = a.getWindowManager();
3001 WindowManager.LayoutParams l = r.window.getAttributes();
3002 a.mDecor = decor;
3003 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
3004 l.softInputMode |= forwardBit;
3005 if (a.mVisibleFromClient) {
3006 a.mWindowAdded = true;
3007 wm.addView(decor, l);
3008 }
3009
3010 // If the window has already been added, but during resume
3011 // we started another activity, then don't yet make the
3012 // window visisble.
3013 } else if (a.mStartedActivity) {
3014 if (localLOGV) Log.v(
3015 TAG, "Launch " + r + " mStartedActivity set");
3016 r.hideForNow = true;
3017 }
3018
3019 // The window is now visible if it has been added, we are not
3020 // simply finishing, and we are not starting another activity.
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003021 if (!r.activity.mFinished && !a.mStartedActivity
3022 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 if (r.newConfig != null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003024 if (DEBUG_CONFIGURATION) Log.v(TAG, "Resuming activity "
3025 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 performConfigurationChanged(r.activity, r.newConfig);
3027 r.newConfig = null;
3028 }
3029 if (localLOGV) Log.v(TAG, "Resuming " + r + " with isForward="
3030 + isForward);
3031 WindowManager.LayoutParams l = r.window.getAttributes();
3032 if ((l.softInputMode
3033 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
3034 != forwardBit) {
3035 l.softInputMode = (l.softInputMode
3036 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
3037 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003038 if (r.activity.mVisibleFromClient) {
3039 ViewManager wm = a.getWindowManager();
3040 View decor = r.window.getDecorView();
3041 wm.updateViewLayout(decor, l);
3042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 }
3044 r.activity.mVisibleFromServer = true;
3045 mNumVisibleActivities++;
3046 if (r.activity.mVisibleFromClient) {
3047 r.activity.makeVisible();
3048 }
3049 }
3050
3051 r.nextIdle = mNewActivities;
3052 mNewActivities = r;
3053 if (localLOGV) Log.v(
3054 TAG, "Scheduling idle handler for " + r);
3055 Looper.myQueue().addIdleHandler(new Idler());
3056
3057 } else {
3058 // If an exception was thrown when trying to resume, then
3059 // just end this activity.
3060 try {
3061 ActivityManagerNative.getDefault()
3062 .finishActivity(token, Activity.RESULT_CANCELED, null);
3063 } catch (RemoteException ex) {
3064 }
3065 }
3066 }
3067
3068 private int mThumbnailWidth = -1;
3069 private int mThumbnailHeight = -1;
3070
3071 private final Bitmap createThumbnailBitmap(ActivityRecord r) {
3072 Bitmap thumbnail = null;
3073 try {
3074 int w = mThumbnailWidth;
3075 int h;
3076 if (w < 0) {
3077 Resources res = r.activity.getResources();
3078 mThumbnailHeight = h =
3079 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
3080
3081 mThumbnailWidth = w =
3082 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
3083 } else {
3084 h = mThumbnailHeight;
3085 }
3086
3087 // XXX Only set hasAlpha if needed?
3088 thumbnail = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
3089 thumbnail.eraseColor(0);
3090 Canvas cv = new Canvas(thumbnail);
3091 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
3092 thumbnail = null;
3093 }
3094 } catch (Exception e) {
3095 if (!mInstrumentation.onException(r.activity, e)) {
3096 throw new RuntimeException(
3097 "Unable to create thumbnail of "
3098 + r.intent.getComponent().toShortString()
3099 + ": " + e.toString(), e);
3100 }
3101 thumbnail = null;
3102 }
3103
3104 return thumbnail;
3105 }
3106
3107 private final void handlePauseActivity(IBinder token, boolean finished,
3108 boolean userLeaving, int configChanges) {
3109 ActivityRecord r = mActivities.get(token);
3110 if (r != null) {
3111 //Log.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
3112 if (userLeaving) {
3113 performUserLeavingActivity(r);
3114 }
Bob Leee5408332009-09-04 18:31:17 -07003115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 r.activity.mConfigChangeFlags |= configChanges;
3117 Bundle state = performPauseActivity(token, finished, true);
3118
3119 // Tell the activity manager we have paused.
3120 try {
3121 ActivityManagerNative.getDefault().activityPaused(token, state);
3122 } catch (RemoteException ex) {
3123 }
3124 }
3125 }
3126
3127 final void performUserLeavingActivity(ActivityRecord r) {
3128 mInstrumentation.callActivityOnUserLeaving(r.activity);
3129 }
3130
3131 final Bundle performPauseActivity(IBinder token, boolean finished,
3132 boolean saveState) {
3133 ActivityRecord r = mActivities.get(token);
3134 return r != null ? performPauseActivity(r, finished, saveState) : null;
3135 }
3136
3137 final Bundle performPauseActivity(ActivityRecord r, boolean finished,
3138 boolean saveState) {
3139 if (r.paused) {
3140 if (r.activity.mFinished) {
3141 // If we are finishing, we won't call onResume() in certain cases.
3142 // So here we likewise don't want to call onPause() if the activity
3143 // isn't resumed.
3144 return null;
3145 }
3146 RuntimeException e = new RuntimeException(
3147 "Performing pause of activity that is not resumed: "
3148 + r.intent.getComponent().toShortString());
3149 Log.e(TAG, e.getMessage(), e);
3150 }
3151 Bundle state = null;
3152 if (finished) {
3153 r.activity.mFinished = true;
3154 }
3155 try {
3156 // Next have the activity save its current state and managed dialogs...
3157 if (!r.activity.mFinished && saveState) {
3158 state = new Bundle();
3159 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
3160 r.state = state;
3161 }
3162 // Now we are idle.
3163 r.activity.mCalled = false;
3164 mInstrumentation.callActivityOnPause(r.activity);
3165 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
3166 if (!r.activity.mCalled) {
3167 throw new SuperNotCalledException(
3168 "Activity " + r.intent.getComponent().toShortString() +
3169 " did not call through to super.onPause()");
3170 }
3171
3172 } catch (SuperNotCalledException e) {
3173 throw e;
3174
3175 } catch (Exception e) {
3176 if (!mInstrumentation.onException(r.activity, e)) {
3177 throw new RuntimeException(
3178 "Unable to pause activity "
3179 + r.intent.getComponent().toShortString()
3180 + ": " + e.toString(), e);
3181 }
3182 }
3183 r.paused = true;
3184 return state;
3185 }
3186
3187 final void performStopActivity(IBinder token) {
3188 ActivityRecord r = mActivities.get(token);
3189 performStopActivityInner(r, null, false);
3190 }
3191
3192 private static class StopInfo {
3193 Bitmap thumbnail;
3194 CharSequence description;
3195 }
3196
3197 private final class ProviderRefCount {
3198 public int count;
3199 ProviderRefCount(int pCount) {
3200 count = pCount;
3201 }
3202 }
3203
3204 private final void performStopActivityInner(ActivityRecord r,
3205 StopInfo info, boolean keepShown) {
3206 if (localLOGV) Log.v(TAG, "Performing stop of " + r);
3207 if (r != null) {
3208 if (!keepShown && r.stopped) {
3209 if (r.activity.mFinished) {
3210 // If we are finishing, we won't call onResume() in certain
3211 // cases. So here we likewise don't want to call onStop()
3212 // if the activity isn't resumed.
3213 return;
3214 }
3215 RuntimeException e = new RuntimeException(
3216 "Performing stop of activity that is not resumed: "
3217 + r.intent.getComponent().toShortString());
3218 Log.e(TAG, e.getMessage(), e);
3219 }
3220
3221 if (info != null) {
3222 try {
3223 // First create a thumbnail for the activity...
3224 //info.thumbnail = createThumbnailBitmap(r);
3225 info.description = r.activity.onCreateDescription();
3226 } catch (Exception e) {
3227 if (!mInstrumentation.onException(r.activity, e)) {
3228 throw new RuntimeException(
3229 "Unable to save state of activity "
3230 + r.intent.getComponent().toShortString()
3231 + ": " + e.toString(), e);
3232 }
3233 }
3234 }
3235
3236 if (!keepShown) {
3237 try {
3238 // Now we are idle.
3239 r.activity.performStop();
3240 } catch (Exception e) {
3241 if (!mInstrumentation.onException(r.activity, e)) {
3242 throw new RuntimeException(
3243 "Unable to stop activity "
3244 + r.intent.getComponent().toShortString()
3245 + ": " + e.toString(), e);
3246 }
3247 }
3248 r.stopped = true;
3249 }
3250
3251 r.paused = true;
3252 }
3253 }
3254
3255 private final void updateVisibility(ActivityRecord r, boolean show) {
3256 View v = r.activity.mDecor;
3257 if (v != null) {
3258 if (show) {
3259 if (!r.activity.mVisibleFromServer) {
3260 r.activity.mVisibleFromServer = true;
3261 mNumVisibleActivities++;
3262 if (r.activity.mVisibleFromClient) {
3263 r.activity.makeVisible();
3264 }
3265 }
3266 if (r.newConfig != null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003267 if (DEBUG_CONFIGURATION) Log.v(TAG, "Updating activity vis "
3268 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 performConfigurationChanged(r.activity, r.newConfig);
3270 r.newConfig = null;
3271 }
3272 } else {
3273 if (r.activity.mVisibleFromServer) {
3274 r.activity.mVisibleFromServer = false;
3275 mNumVisibleActivities--;
3276 v.setVisibility(View.INVISIBLE);
3277 }
3278 }
3279 }
3280 }
3281
3282 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
3283 ActivityRecord r = mActivities.get(token);
3284 r.activity.mConfigChangeFlags |= configChanges;
3285
3286 StopInfo info = new StopInfo();
3287 performStopActivityInner(r, info, show);
3288
3289 if (localLOGV) Log.v(
3290 TAG, "Finishing stop of " + r + ": show=" + show
3291 + " win=" + r.window);
3292
3293 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07003294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 // Tell activity manager we have been stopped.
3296 try {
3297 ActivityManagerNative.getDefault().activityStopped(
3298 r.token, info.thumbnail, info.description);
3299 } catch (RemoteException ex) {
3300 }
3301 }
3302
3303 final void performRestartActivity(IBinder token) {
3304 ActivityRecord r = mActivities.get(token);
3305 if (r.stopped) {
3306 r.activity.performRestart();
3307 r.stopped = false;
3308 }
3309 }
3310
3311 private final void handleWindowVisibility(IBinder token, boolean show) {
3312 ActivityRecord r = mActivities.get(token);
3313 if (!show && !r.stopped) {
3314 performStopActivityInner(r, null, show);
3315 } else if (show && r.stopped) {
3316 // If we are getting ready to gc after going to the background, well
3317 // we are back active so skip it.
3318 unscheduleGcIdler();
3319
3320 r.activity.performRestart();
3321 r.stopped = false;
3322 }
3323 if (r.activity.mDecor != null) {
3324 if (Config.LOGV) Log.v(
3325 TAG, "Handle window " + r + " visibility: " + show);
3326 updateVisibility(r, show);
3327 }
3328 }
3329
3330 private final void deliverResults(ActivityRecord r, List<ResultInfo> results) {
3331 final int N = results.size();
3332 for (int i=0; i<N; i++) {
3333 ResultInfo ri = results.get(i);
3334 try {
3335 if (ri.mData != null) {
3336 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3337 }
Chris Tate8a7dc172009-03-24 20:11:42 -07003338 if (DEBUG_RESULTS) Log.v(TAG,
3339 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 r.activity.dispatchActivityResult(ri.mResultWho,
3341 ri.mRequestCode, ri.mResultCode, ri.mData);
3342 } catch (Exception e) {
3343 if (!mInstrumentation.onException(r.activity, e)) {
3344 throw new RuntimeException(
3345 "Failure delivering result " + ri + " to activity "
3346 + r.intent.getComponent().toShortString()
3347 + ": " + e.toString(), e);
3348 }
3349 }
3350 }
3351 }
3352
3353 private final void handleSendResult(ResultData res) {
3354 ActivityRecord r = mActivities.get(res.token);
Chris Tate8a7dc172009-03-24 20:11:42 -07003355 if (DEBUG_RESULTS) Log.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 if (r != null) {
3357 final boolean resumed = !r.paused;
3358 if (!r.activity.mFinished && r.activity.mDecor != null
3359 && r.hideForNow && resumed) {
3360 // We had hidden the activity because it started another
3361 // one... we have gotten a result back and we are not
3362 // paused, so make sure our window is visible.
3363 updateVisibility(r, true);
3364 }
3365 if (resumed) {
3366 try {
3367 // Now we are idle.
3368 r.activity.mCalled = false;
3369 mInstrumentation.callActivityOnPause(r.activity);
3370 if (!r.activity.mCalled) {
3371 throw new SuperNotCalledException(
3372 "Activity " + r.intent.getComponent().toShortString()
3373 + " did not call through to super.onPause()");
3374 }
3375 } catch (SuperNotCalledException e) {
3376 throw e;
3377 } catch (Exception e) {
3378 if (!mInstrumentation.onException(r.activity, e)) {
3379 throw new RuntimeException(
3380 "Unable to pause activity "
3381 + r.intent.getComponent().toShortString()
3382 + ": " + e.toString(), e);
3383 }
3384 }
3385 }
3386 deliverResults(r, res.results);
3387 if (resumed) {
3388 mInstrumentation.callActivityOnResume(r.activity);
3389 }
3390 }
3391 }
3392
3393 public final ActivityRecord performDestroyActivity(IBinder token, boolean finishing) {
3394 return performDestroyActivity(token, finishing, 0, false);
3395 }
3396
3397 private final ActivityRecord performDestroyActivity(IBinder token, boolean finishing,
3398 int configChanges, boolean getNonConfigInstance) {
3399 ActivityRecord r = mActivities.get(token);
3400 if (localLOGV) Log.v(TAG, "Performing finish of " + r);
3401 if (r != null) {
3402 r.activity.mConfigChangeFlags |= configChanges;
3403 if (finishing) {
3404 r.activity.mFinished = true;
3405 }
3406 if (!r.paused) {
3407 try {
3408 r.activity.mCalled = false;
3409 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003410 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 r.activity.getComponentName().getClassName());
3412 if (!r.activity.mCalled) {
3413 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003414 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 + " did not call through to super.onPause()");
3416 }
3417 } catch (SuperNotCalledException e) {
3418 throw e;
3419 } catch (Exception e) {
3420 if (!mInstrumentation.onException(r.activity, e)) {
3421 throw new RuntimeException(
3422 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003423 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 + ": " + e.toString(), e);
3425 }
3426 }
3427 r.paused = true;
3428 }
3429 if (!r.stopped) {
3430 try {
3431 r.activity.performStop();
3432 } catch (SuperNotCalledException e) {
3433 throw e;
3434 } catch (Exception e) {
3435 if (!mInstrumentation.onException(r.activity, e)) {
3436 throw new RuntimeException(
3437 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003438 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 + ": " + e.toString(), e);
3440 }
3441 }
3442 r.stopped = true;
3443 }
3444 if (getNonConfigInstance) {
3445 try {
3446 r.lastNonConfigurationInstance
3447 = r.activity.onRetainNonConfigurationInstance();
3448 } catch (Exception e) {
3449 if (!mInstrumentation.onException(r.activity, e)) {
3450 throw new RuntimeException(
3451 "Unable to retain activity "
3452 + r.intent.getComponent().toShortString()
3453 + ": " + e.toString(), e);
3454 }
3455 }
3456 try {
3457 r.lastNonConfigurationChildInstances
3458 = r.activity.onRetainNonConfigurationChildInstances();
3459 } catch (Exception e) {
3460 if (!mInstrumentation.onException(r.activity, e)) {
3461 throw new RuntimeException(
3462 "Unable to retain child activities "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003463 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003464 + ": " + e.toString(), e);
3465 }
3466 }
Bob Leee5408332009-09-04 18:31:17 -07003467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 }
3469 try {
3470 r.activity.mCalled = false;
3471 r.activity.onDestroy();
3472 if (!r.activity.mCalled) {
3473 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003474 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 " did not call through to super.onDestroy()");
3476 }
3477 if (r.window != null) {
3478 r.window.closeAllPanels();
3479 }
3480 } catch (SuperNotCalledException e) {
3481 throw e;
3482 } catch (Exception e) {
3483 if (!mInstrumentation.onException(r.activity, e)) {
3484 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003485 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3486 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 }
3488 }
3489 }
3490 mActivities.remove(token);
3491
3492 return r;
3493 }
3494
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003495 private static String safeToComponentShortString(Intent intent) {
3496 ComponentName component = intent.getComponent();
3497 return component == null ? "[Unknown]" : component.toShortString();
3498 }
3499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 private final void handleDestroyActivity(IBinder token, boolean finishing,
3501 int configChanges, boolean getNonConfigInstance) {
3502 ActivityRecord r = performDestroyActivity(token, finishing,
3503 configChanges, getNonConfigInstance);
3504 if (r != null) {
3505 WindowManager wm = r.activity.getWindowManager();
3506 View v = r.activity.mDecor;
3507 if (v != null) {
3508 if (r.activity.mVisibleFromServer) {
3509 mNumVisibleActivities--;
3510 }
3511 IBinder wtoken = v.getWindowToken();
3512 if (r.activity.mWindowAdded) {
3513 wm.removeViewImmediate(v);
3514 }
3515 if (wtoken != null) {
3516 WindowManagerImpl.getDefault().closeAll(wtoken,
3517 r.activity.getClass().getName(), "Activity");
3518 }
3519 r.activity.mDecor = null;
3520 }
3521 WindowManagerImpl.getDefault().closeAll(token,
3522 r.activity.getClass().getName(), "Activity");
3523
3524 // Mocked out contexts won't be participating in the normal
3525 // process lifecycle, but if we're running with a proper
3526 // ApplicationContext we need to have it tear down things
3527 // cleanly.
3528 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003529 if (c instanceof ContextImpl) {
3530 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 r.activity.getClass().getName(), "Activity");
3532 }
3533 }
3534 if (finishing) {
3535 try {
3536 ActivityManagerNative.getDefault().activityDestroyed(token);
3537 } catch (RemoteException ex) {
3538 // If the system process has died, it's game over for everyone.
3539 }
3540 }
3541 }
3542
3543 private final void handleRelaunchActivity(ActivityRecord tmp, int configChanges) {
3544 // If we are getting ready to gc after going to the background, well
3545 // we are back active so skip it.
3546 unscheduleGcIdler();
3547
3548 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07003549
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003550 if (DEBUG_CONFIGURATION) Log.v(TAG, "Relaunching activity "
3551 + tmp.token + " with configChanges=0x"
3552 + Integer.toHexString(configChanges));
3553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 // First: make sure we have the most recent configuration and most
3555 // recent version of the activity, or skip it if some previous call
3556 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003557 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 int N = mRelaunchingActivities.size();
3559 IBinder token = tmp.token;
3560 tmp = null;
3561 for (int i=0; i<N; i++) {
3562 ActivityRecord r = mRelaunchingActivities.get(i);
3563 if (r.token == token) {
3564 tmp = r;
3565 mRelaunchingActivities.remove(i);
3566 i--;
3567 N--;
3568 }
3569 }
Bob Leee5408332009-09-04 18:31:17 -07003570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 if (tmp == null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003572 if (DEBUG_CONFIGURATION) Log.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 return;
3574 }
Bob Leee5408332009-09-04 18:31:17 -07003575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 if (mPendingConfiguration != null) {
3577 changedConfig = mPendingConfiguration;
3578 mPendingConfiguration = null;
3579 }
3580 }
Bob Leee5408332009-09-04 18:31:17 -07003581
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003582 if (tmp.createdConfig != null) {
3583 // If the activity manager is passing us its current config,
3584 // assume that is really what we want regardless of what we
3585 // may have pending.
3586 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003587 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
3588 && mConfiguration.diff(tmp.createdConfig) != 0)) {
3589 if (changedConfig == null
3590 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
3591 changedConfig = tmp.createdConfig;
3592 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003593 }
3594 }
3595
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003596 if (DEBUG_CONFIGURATION) Log.v(TAG, "Relaunching activity "
3597 + tmp.token + ": changedConfig=" + changedConfig);
3598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 // If there was a pending configuration change, execute it first.
3600 if (changedConfig != null) {
3601 handleConfigurationChanged(changedConfig);
3602 }
Bob Leee5408332009-09-04 18:31:17 -07003603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 ActivityRecord r = mActivities.get(tmp.token);
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003605 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606 if (r == null) {
3607 return;
3608 }
Bob Leee5408332009-09-04 18:31:17 -07003609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003611 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 Bundle savedState = null;
3614 if (!r.paused) {
3615 savedState = performPauseActivity(r.token, false, true);
3616 }
Bob Leee5408332009-09-04 18:31:17 -07003617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 r.activity = null;
3621 r.window = null;
3622 r.hideForNow = false;
3623 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003624 // Merge any pending results and pending intents; don't just replace them
3625 if (tmp.pendingResults != null) {
3626 if (r.pendingResults == null) {
3627 r.pendingResults = tmp.pendingResults;
3628 } else {
3629 r.pendingResults.addAll(tmp.pendingResults);
3630 }
3631 }
3632 if (tmp.pendingIntents != null) {
3633 if (r.pendingIntents == null) {
3634 r.pendingIntents = tmp.pendingIntents;
3635 } else {
3636 r.pendingIntents.addAll(tmp.pendingIntents);
3637 }
3638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 r.startsNotResumed = tmp.startsNotResumed;
3640 if (savedState != null) {
3641 r.state = savedState;
3642 }
Bob Leee5408332009-09-04 18:31:17 -07003643
Christopher Tateb70f3df2009-04-07 16:07:59 -07003644 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 }
3646
3647 private final void handleRequestThumbnail(IBinder token) {
3648 ActivityRecord r = mActivities.get(token);
3649 Bitmap thumbnail = createThumbnailBitmap(r);
3650 CharSequence description = null;
3651 try {
3652 description = r.activity.onCreateDescription();
3653 } catch (Exception e) {
3654 if (!mInstrumentation.onException(r.activity, e)) {
3655 throw new RuntimeException(
3656 "Unable to create description of activity "
3657 + r.intent.getComponent().toShortString()
3658 + ": " + e.toString(), e);
3659 }
3660 }
3661 //System.out.println("Reporting top thumbnail " + thumbnail);
3662 try {
3663 ActivityManagerNative.getDefault().reportThumbnail(
3664 token, thumbnail, description);
3665 } catch (RemoteException ex) {
3666 }
3667 }
3668
3669 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
3670 boolean allActivities, Configuration newConfig) {
3671 ArrayList<ComponentCallbacks> callbacks
3672 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 if (mActivities.size() > 0) {
3675 Iterator<ActivityRecord> it = mActivities.values().iterator();
3676 while (it.hasNext()) {
3677 ActivityRecord ar = it.next();
3678 Activity a = ar.activity;
3679 if (a != null) {
3680 if (!ar.activity.mFinished && (allActivities ||
3681 (a != null && !ar.paused))) {
3682 // If the activity is currently resumed, its configuration
3683 // needs to change right now.
3684 callbacks.add(a);
3685 } else if (newConfig != null) {
3686 // Otherwise, we will tell it about the change
3687 // the next time it is resumed or shown. Note that
3688 // the activity manager may, before then, decide the
3689 // activity needs to be destroyed to handle its new
3690 // configuration.
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003691 if (DEBUG_CONFIGURATION) Log.v(TAG, "Setting activity "
3692 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 ar.newConfig = newConfig;
3694 }
3695 }
3696 }
3697 }
3698 if (mServices.size() > 0) {
3699 Iterator<Service> it = mServices.values().iterator();
3700 while (it.hasNext()) {
3701 callbacks.add(it.next());
3702 }
3703 }
3704 synchronized (mProviderMap) {
3705 if (mLocalProviders.size() > 0) {
3706 Iterator<ProviderRecord> it = mLocalProviders.values().iterator();
3707 while (it.hasNext()) {
3708 callbacks.add(it.next().mLocalProvider);
3709 }
3710 }
3711 }
3712 final int N = mAllApplications.size();
3713 for (int i=0; i<N; i++) {
3714 callbacks.add(mAllApplications.get(i));
3715 }
Bob Leee5408332009-09-04 18:31:17 -07003716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 return callbacks;
3718 }
Bob Leee5408332009-09-04 18:31:17 -07003719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 private final void performConfigurationChanged(
3721 ComponentCallbacks cb, Configuration config) {
3722 // Only for Activity objects, check that they actually call up to their
3723 // superclass implementation. ComponentCallbacks is an interface, so
3724 // we check the runtime type and act accordingly.
3725 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3726 if (activity != null) {
3727 activity.mCalled = false;
3728 }
Bob Leee5408332009-09-04 18:31:17 -07003729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 boolean shouldChangeConfig = false;
3731 if ((activity == null) || (activity.mCurrentConfig == null)) {
3732 shouldChangeConfig = true;
3733 } else {
Bob Leee5408332009-09-04 18:31:17 -07003734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 // If the new config is the same as the config this Activity
3736 // is already running with then don't bother calling
3737 // onConfigurationChanged
3738 int diff = activity.mCurrentConfig.diff(config);
3739 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07003740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 // If this activity doesn't handle any of the config changes
3742 // then don't bother calling onConfigurationChanged as we're
3743 // going to destroy it.
3744 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
3745 shouldChangeConfig = true;
3746 }
3747 }
3748 }
Bob Leee5408332009-09-04 18:31:17 -07003749
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003750 if (DEBUG_CONFIGURATION) Log.v(TAG, "Config callback " + cb
3751 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 if (shouldChangeConfig) {
3753 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 if (activity != null) {
3756 if (!activity.mCalled) {
3757 throw new SuperNotCalledException(
3758 "Activity " + activity.getLocalClassName() +
3759 " did not call through to super.onConfigurationChanged()");
3760 }
3761 activity.mConfigChangeFlags = 0;
3762 activity.mCurrentConfig = new Configuration(config);
3763 }
3764 }
3765 }
3766
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003767 final void applyConfigurationToResourcesLocked(Configuration config) {
3768 if (mResConfiguration == null) {
3769 mResConfiguration = new Configuration();
3770 }
3771 if (!mResConfiguration.isOtherSeqNewer(config)) {
3772 return;
3773 }
3774 mResConfiguration.updateFrom(config);
3775 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07003776
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003777 // set it for java, this also affects newly created Resources
3778 if (config.locale != null) {
3779 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 }
Bob Leee5408332009-09-04 18:31:17 -07003781
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003782 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07003783
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003784 ContextImpl.ApplicationPackageManager.configurationChanged();
3785 //Log.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003786
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003787 Iterator<WeakReference<Resources>> it =
3788 mActiveResources.values().iterator();
3789 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3790 // mActiveResources.entrySet().iterator();
3791 while (it.hasNext()) {
3792 WeakReference<Resources> v = it.next();
3793 Resources r = v.get();
3794 if (r != null) {
3795 r.updateConfiguration(config, dm);
3796 //Log.i(TAG, "Updated app resources " + v.getKey()
3797 // + " " + r + ": " + r.getConfiguration());
3798 } else {
3799 //Log.i(TAG, "Removing old resources " + v.getKey());
3800 it.remove();
3801 }
3802 }
3803 }
3804
3805 final void handleConfigurationChanged(Configuration config) {
3806
3807 ArrayList<ComponentCallbacks> callbacks = null;
3808
3809 synchronized (mPackages) {
3810 if (mPendingConfiguration != null) {
3811 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3812 config = mPendingConfiguration;
3813 }
3814 mPendingConfiguration = null;
3815 }
3816
3817 if (config == null) {
3818 return;
3819 }
3820
3821 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handle configuration changed: "
3822 + config);
3823
3824 applyConfigurationToResourcesLocked(config);
3825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 if (mConfiguration == null) {
3827 mConfiguration = new Configuration();
3828 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003829 if (!mConfiguration.isOtherSeqNewer(config)) {
3830 return;
3831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 callbacks = collectComponentCallbacksLocked(false, config);
3835 }
Bob Leee5408332009-09-04 18:31:17 -07003836
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003837 if (callbacks != null) {
3838 final int N = callbacks.size();
3839 for (int i=0; i<N; i++) {
3840 performConfigurationChanged(callbacks.get(i), config);
3841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 }
3843 }
3844
3845 final void handleActivityConfigurationChanged(IBinder token) {
3846 ActivityRecord r = mActivities.get(token);
3847 if (r == null || r.activity == null) {
3848 return;
3849 }
Bob Leee5408332009-09-04 18:31:17 -07003850
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003851 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handle activity config changed: "
3852 + r.activityInfo.name);
3853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 performConfigurationChanged(r.activity, mConfiguration);
3855 }
3856
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003857 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003858 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003859 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003860 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3861 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003862 } catch (RuntimeException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003863 Log.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003864 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003865 } finally {
3866 try {
3867 pcd.fd.close();
3868 } catch (IOException e) {
3869 Log.w(TAG, "Failure closing profile fd", e);
3870 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003871 }
3872 } else {
3873 Debug.stopMethodTracing();
3874 }
3875 }
Bob Leee5408332009-09-04 18:31:17 -07003876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 final void handleLowMemory() {
3878 ArrayList<ComponentCallbacks> callbacks
3879 = new ArrayList<ComponentCallbacks>();
3880
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003881 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 callbacks = collectComponentCallbacksLocked(true, null);
3883 }
Bob Leee5408332009-09-04 18:31:17 -07003884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 final int N = callbacks.size();
3886 for (int i=0; i<N; i++) {
3887 callbacks.get(i).onLowMemory();
3888 }
3889
Chris Tatece229052009-03-25 16:44:52 -07003890 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3891 if (Process.myUid() != Process.SYSTEM_UID) {
3892 int sqliteReleased = SQLiteDatabase.releaseMemory();
3893 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3894 }
Bob Leee5408332009-09-04 18:31:17 -07003895
Mike Reedcaf0df12009-04-27 14:32:05 -04003896 // Ask graphics to free up as much as possible (font/image caches)
3897 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898
3899 BinderInternal.forceGc("mem");
3900 }
3901
3902 private final void handleBindApplication(AppBindData data) {
3903 mBoundApplication = data;
3904 mConfiguration = new Configuration(data.config);
3905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003907 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 android.ddm.DdmHandleAppName.setAppName(data.processName);
3909
3910 /*
3911 * Before spawning a new process, reset the time zone to be the system time zone.
3912 * This needs to be done because the system time zone could have changed after the
3913 * the spawning of this process. Without doing this this process would have the incorrect
3914 * system time zone.
3915 */
3916 TimeZone.setDefault(null);
3917
3918 /*
3919 * Initialize the default locale in this process for the reasons we set the time zone.
3920 */
3921 Locale.setDefault(data.config.locale);
3922
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003923 /*
3924 * Update the system configuration since its preloaded and might not
3925 * reflect configuration changes. The configuration object passed
3926 * in AppBindData can be safely assumed to be up to date
3927 */
3928 Resources.getSystem().updateConfiguration(mConfiguration, null);
3929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 data.info = getPackageInfoNoCheck(data.appInfo);
3931
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003932 /**
3933 * Switch this process to density compatibility mode if needed.
3934 */
3935 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3936 == 0) {
3937 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3938 }
Bob Leee5408332009-09-04 18:31:17 -07003939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3941 // XXX should have option to change the port.
3942 Debug.changeDebugPort(8100);
3943 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
3944 Log.w(TAG, "Application " + data.info.getPackageName()
3945 + " is waiting for the debugger on port 8100...");
3946
3947 IActivityManager mgr = ActivityManagerNative.getDefault();
3948 try {
3949 mgr.showWaitingForDebugger(mAppThread, true);
3950 } catch (RemoteException ex) {
3951 }
3952
3953 Debug.waitForDebugger();
3954
3955 try {
3956 mgr.showWaitingForDebugger(mAppThread, false);
3957 } catch (RemoteException ex) {
3958 }
3959
3960 } else {
3961 Log.w(TAG, "Application " + data.info.getPackageName()
3962 + " can be debugged on port 8100...");
3963 }
3964 }
3965
3966 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003967 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 appContext.init(data.info, null, this);
3969 InstrumentationInfo ii = null;
3970 try {
3971 ii = appContext.getPackageManager().
3972 getInstrumentationInfo(data.instrumentationName, 0);
3973 } catch (PackageManager.NameNotFoundException e) {
3974 }
3975 if (ii == null) {
3976 throw new RuntimeException(
3977 "Unable to find instrumentation info for: "
3978 + data.instrumentationName);
3979 }
3980
3981 mInstrumentationAppDir = ii.sourceDir;
3982 mInstrumentationAppPackage = ii.packageName;
3983 mInstrumentedAppDir = data.info.getAppDir();
3984
3985 ApplicationInfo instrApp = new ApplicationInfo();
3986 instrApp.packageName = ii.packageName;
3987 instrApp.sourceDir = ii.sourceDir;
3988 instrApp.publicSourceDir = ii.publicSourceDir;
3989 instrApp.dataDir = ii.dataDir;
3990 PackageInfo pi = getPackageInfo(instrApp,
3991 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003992 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 instrContext.init(pi, null, this);
3994
3995 try {
3996 java.lang.ClassLoader cl = instrContext.getClassLoader();
3997 mInstrumentation = (Instrumentation)
3998 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3999 } catch (Exception e) {
4000 throw new RuntimeException(
4001 "Unable to instantiate instrumentation "
4002 + data.instrumentationName + ": " + e.toString(), e);
4003 }
4004
4005 mInstrumentation.init(this, instrContext, appContext,
4006 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
4007
4008 if (data.profileFile != null && !ii.handleProfiling) {
4009 data.handlingProfiling = true;
4010 File file = new File(data.profileFile);
4011 file.getParentFile().mkdirs();
4012 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
4013 }
4014
4015 try {
4016 mInstrumentation.onCreate(data.instrumentationArgs);
4017 }
4018 catch (Exception e) {
4019 throw new RuntimeException(
4020 "Exception thrown in onCreate() of "
4021 + data.instrumentationName + ": " + e.toString(), e);
4022 }
4023
4024 } else {
4025 mInstrumentation = new Instrumentation();
4026 }
4027
Christopher Tate181fafa2009-05-14 11:12:14 -07004028 // If the app is being launched for full backup or restore, bring it up in
4029 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08004030 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 mInitialApplication = app;
4032
4033 List<ProviderInfo> providers = data.providers;
4034 if (providers != null) {
4035 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004036 // For process that contain content providers, we want to
4037 // ensure that the JIT is enabled "at some point".
4038 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 }
4040
4041 try {
4042 mInstrumentation.callApplicationOnCreate(app);
4043 } catch (Exception e) {
4044 if (!mInstrumentation.onException(app, e)) {
4045 throw new RuntimeException(
4046 "Unable to create application " + app.getClass().getName()
4047 + ": " + e.toString(), e);
4048 }
4049 }
4050 }
4051
4052 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
4053 IActivityManager am = ActivityManagerNative.getDefault();
4054 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
4055 Debug.stopMethodTracing();
4056 }
4057 //Log.i(TAG, "am: " + ActivityManagerNative.getDefault()
4058 // + ", app thr: " + mAppThread);
4059 try {
4060 am.finishInstrumentation(mAppThread, resultCode, results);
4061 } catch (RemoteException ex) {
4062 }
4063 }
4064
4065 private final void installContentProviders(
4066 Context context, List<ProviderInfo> providers) {
4067 final ArrayList<IActivityManager.ContentProviderHolder> results =
4068 new ArrayList<IActivityManager.ContentProviderHolder>();
4069
4070 Iterator<ProviderInfo> i = providers.iterator();
4071 while (i.hasNext()) {
4072 ProviderInfo cpi = i.next();
4073 StringBuilder buf = new StringBuilder(128);
4074 buf.append("Publishing provider ");
4075 buf.append(cpi.authority);
4076 buf.append(": ");
4077 buf.append(cpi.name);
4078 Log.i(TAG, buf.toString());
4079 IContentProvider cp = installProvider(context, null, cpi, false);
4080 if (cp != null) {
4081 IActivityManager.ContentProviderHolder cph =
4082 new IActivityManager.ContentProviderHolder(cpi);
4083 cph.provider = cp;
4084 results.add(cph);
4085 // Don't ever unload this provider from the process.
4086 synchronized(mProviderMap) {
4087 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
4088 }
4089 }
4090 }
4091
4092 try {
4093 ActivityManagerNative.getDefault().publishContentProviders(
4094 getApplicationThread(), results);
4095 } catch (RemoteException ex) {
4096 }
4097 }
4098
4099 private final IContentProvider getProvider(Context context, String name) {
4100 synchronized(mProviderMap) {
4101 final ProviderRecord pr = mProviderMap.get(name);
4102 if (pr != null) {
4103 return pr.mProvider;
4104 }
4105 }
4106
4107 IActivityManager.ContentProviderHolder holder = null;
4108 try {
4109 holder = ActivityManagerNative.getDefault().getContentProvider(
4110 getApplicationThread(), name);
4111 } catch (RemoteException ex) {
4112 }
4113 if (holder == null) {
4114 Log.e(TAG, "Failed to find provider info for " + name);
4115 return null;
4116 }
4117 if (holder.permissionFailure != null) {
4118 throw new SecurityException("Permission " + holder.permissionFailure
4119 + " required for provider " + name);
4120 }
4121
4122 IContentProvider prov = installProvider(context, holder.provider,
4123 holder.info, true);
4124 //Log.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
4125 if (holder.noReleaseNeeded || holder.provider == null) {
4126 // We are not going to release the provider if it is an external
4127 // provider that doesn't care about being released, or if it is
4128 // a local provider running in this process.
4129 //Log.i(TAG, "*** NO RELEASE NEEDED");
4130 synchronized(mProviderMap) {
4131 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
4132 }
4133 }
4134 return prov;
4135 }
4136
4137 public final IContentProvider acquireProvider(Context c, String name) {
4138 IContentProvider provider = getProvider(c, name);
4139 if(provider == null)
4140 return null;
4141 IBinder jBinder = provider.asBinder();
4142 synchronized(mProviderMap) {
4143 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4144 if(prc == null) {
4145 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4146 } else {
4147 prc.count++;
4148 } //end else
4149 } //end synchronized
4150 return provider;
4151 }
4152
4153 public final boolean releaseProvider(IContentProvider provider) {
4154 if(provider == null) {
4155 return false;
4156 }
4157 IBinder jBinder = provider.asBinder();
4158 synchronized(mProviderMap) {
4159 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4160 if(prc == null) {
4161 if(localLOGV) Log.v(TAG, "releaseProvider::Weird shouldnt be here");
4162 return false;
4163 } else {
4164 prc.count--;
4165 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004166 // Schedule the actual remove asynchronously, since we
4167 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004168 // TODO: it would be nice to post a delayed message, so
4169 // if we come back and need the same provider quickly
4170 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004171 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4172 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173 } //end if
4174 } //end else
4175 } //end synchronized
4176 return true;
4177 }
4178
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004179 final void completeRemoveProvider(IContentProvider provider) {
4180 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004181 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004182 synchronized(mProviderMap) {
4183 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4184 if(prc != null && prc.count == 0) {
4185 mProviderRefCountMap.remove(jBinder);
4186 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004187 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004188 }
4189 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004190
4191 if (name != null) {
4192 try {
4193 if(localLOGV) Log.v(TAG, "removeProvider::Invoking " +
4194 "ActivityManagerNative.removeContentProvider(" + name);
4195 ActivityManagerNative.getDefault().removeContentProvider(
4196 getApplicationThread(), name);
4197 } catch (RemoteException e) {
4198 //do nothing content provider object is dead any way
4199 } //end catch
4200 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004201 }
4202
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004203 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004205 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 }
4207 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004209 String name = null;
4210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 // remove the provider from mProviderMap
4212 Iterator<ProviderRecord> iter = mProviderMap.values().iterator();
4213 while (iter.hasNext()) {
4214 ProviderRecord pr = iter.next();
4215 IBinder myBinder = pr.mProvider.asBinder();
4216 if (myBinder == providerBinder) {
4217 //find if its published by this process itself
4218 if(pr.mLocalProvider != null) {
4219 if(localLOGV) Log.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004220 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 }
4222 if(localLOGV) Log.v(TAG, "removeProvider::Not local provider Unlinking " +
4223 "death recipient");
4224 //content provider is in another process
4225 myBinder.unlinkToDeath(pr, 0);
4226 iter.remove();
4227 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004228 if(name == null) {
4229 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 }
4231 } //end if myBinder
4232 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004233
4234 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 }
4236
4237 final void removeDeadProvider(String name, IContentProvider provider) {
4238 synchronized(mProviderMap) {
4239 ProviderRecord pr = mProviderMap.get(name);
4240 if (pr.mProvider.asBinder() == provider.asBinder()) {
4241 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004242 ProviderRecord removed = mProviderMap.remove(name);
4243 if (removed != null) {
4244 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 }
4247 }
4248 }
4249
4250 final void removeDeadProviderLocked(String name, IContentProvider provider) {
4251 ProviderRecord pr = mProviderMap.get(name);
4252 if (pr.mProvider.asBinder() == provider.asBinder()) {
4253 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004254 ProviderRecord removed = mProviderMap.remove(name);
4255 if (removed != null) {
4256 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 }
4259 }
4260
4261 private final IContentProvider installProvider(Context context,
4262 IContentProvider provider, ProviderInfo info, boolean noisy) {
4263 ContentProvider localProvider = null;
4264 if (provider == null) {
4265 if (noisy) {
4266 Log.d(TAG, "Loading provider " + info.authority + ": "
4267 + info.name);
4268 }
4269 Context c = null;
4270 ApplicationInfo ai = info.applicationInfo;
4271 if (context.getPackageName().equals(ai.packageName)) {
4272 c = context;
4273 } else if (mInitialApplication != null &&
4274 mInitialApplication.getPackageName().equals(ai.packageName)) {
4275 c = mInitialApplication;
4276 } else {
4277 try {
4278 c = context.createPackageContext(ai.packageName,
4279 Context.CONTEXT_INCLUDE_CODE);
4280 } catch (PackageManager.NameNotFoundException e) {
4281 }
4282 }
4283 if (c == null) {
4284 Log.w(TAG, "Unable to get context for package " +
4285 ai.packageName +
4286 " while loading content provider " +
4287 info.name);
4288 return null;
4289 }
4290 try {
4291 final java.lang.ClassLoader cl = c.getClassLoader();
4292 localProvider = (ContentProvider)cl.
4293 loadClass(info.name).newInstance();
4294 provider = localProvider.getIContentProvider();
4295 if (provider == null) {
4296 Log.e(TAG, "Failed to instantiate class " +
4297 info.name + " from sourceDir " +
4298 info.applicationInfo.sourceDir);
4299 return null;
4300 }
4301 if (Config.LOGV) Log.v(
4302 TAG, "Instantiating local provider " + info.name);
4303 // XXX Need to create the correct context for this provider.
4304 localProvider.attachInfo(c, info);
4305 } catch (java.lang.Exception e) {
4306 if (!mInstrumentation.onException(null, e)) {
4307 throw new RuntimeException(
4308 "Unable to get provider " + info.name
4309 + ": " + e.toString(), e);
4310 }
4311 return null;
4312 }
4313 } else if (localLOGV) {
4314 Log.v(TAG, "Installing external provider " + info.authority + ": "
4315 + info.name);
4316 }
4317
4318 synchronized (mProviderMap) {
4319 // Cache the pointer for the remote provider.
4320 String names[] = PATTERN_SEMICOLON.split(info.authority);
4321 for (int i=0; i<names.length; i++) {
4322 ProviderRecord pr = new ProviderRecord(names[i], provider,
4323 localProvider);
4324 try {
4325 provider.asBinder().linkToDeath(pr, 0);
4326 mProviderMap.put(names[i], pr);
4327 } catch (RemoteException e) {
4328 return null;
4329 }
4330 }
4331 if (localProvider != null) {
4332 mLocalProviders.put(provider.asBinder(),
4333 new ProviderRecord(null, provider, localProvider));
4334 }
4335 }
4336
4337 return provider;
4338 }
4339
4340 private final void attach(boolean system) {
4341 sThreadLocal.set(this);
4342 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004344 ViewRoot.addFirstDrawHandler(new Runnable() {
4345 public void run() {
4346 ensureJitEnabled();
4347 }
4348 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4350 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4351 IActivityManager mgr = ActivityManagerNative.getDefault();
4352 try {
4353 mgr.attachApplication(mAppThread);
4354 } catch (RemoteException ex) {
4355 }
4356 } else {
4357 // Don't set application object here -- if the system crashes,
4358 // we can't display an alert, we just want to die die die.
4359 android.ddm.DdmHandleAppName.setAppName("system_process");
4360 try {
4361 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08004362 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363 context.init(getSystemContext().mPackageInfo, null, this);
4364 Application app = Instrumentation.newApplication(Application.class, context);
4365 mAllApplications.add(app);
4366 mInitialApplication = app;
4367 app.onCreate();
4368 } catch (Exception e) {
4369 throw new RuntimeException(
4370 "Unable to instantiate Application():" + e.toString(), e);
4371 }
4372 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004373
4374 ViewRoot.addConfigCallback(new ComponentCallbacks() {
4375 public void onConfigurationChanged(Configuration newConfig) {
4376 synchronized (mPackages) {
4377 if (mPendingConfiguration == null ||
4378 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
4379 mPendingConfiguration = newConfig;
4380
4381 // We need to apply this change to the resources
4382 // immediately, because upon returning the view
4383 // hierarchy will be informed about it.
4384 applyConfigurationToResourcesLocked(newConfig);
4385 }
4386 }
4387 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
4388 }
4389 public void onLowMemory() {
4390 }
4391 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 }
4393
4394 private final void detach()
4395 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 sThreadLocal.set(null);
4397 }
4398
4399 public static final ActivityThread systemMain() {
4400 ActivityThread thread = new ActivityThread();
4401 thread.attach(true);
4402 return thread;
4403 }
4404
4405 public final void installSystemProviders(List providers) {
4406 if (providers != null) {
4407 installContentProviders(mInitialApplication,
4408 (List<ProviderInfo>)providers);
4409 }
4410 }
4411
4412 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004413 SamplingProfilerIntegration.start();
4414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004415 Process.setArgV0("<pre-initialized>");
4416
4417 Looper.prepareMainLooper();
4418
4419 ActivityThread thread = new ActivityThread();
4420 thread.attach(false);
4421
4422 Looper.loop();
4423
4424 if (Process.supportsProcesses()) {
4425 throw new RuntimeException("Main thread loop unexpectedly exited");
4426 }
4427
4428 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02004429 String name = (thread.mInitialApplication != null)
4430 ? thread.mInitialApplication.getPackageName()
4431 : "<unknown>";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 Log.i(TAG, "Main thread of " + name + " is now exiting");
4433 }
4434}