blob: b116bf8fd3064e0b3de7cf60ff16f6ff6b4425a4 [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;
43import android.net.http.AndroidHttpClient;
44import android.os.Bundle;
45import android.os.Debug;
46import android.os.Handler;
47import android.os.IBinder;
48import android.os.Looper;
49import android.os.Message;
50import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070051import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.Process;
53import android.os.RemoteException;
54import android.os.ServiceManager;
55import android.os.SystemClock;
56import android.util.AndroidRuntimeException;
57import android.util.Config;
58import android.util.DisplayMetrics;
59import android.util.EventLog;
60import android.util.Log;
61import android.view.Display;
62import android.view.View;
63import android.view.ViewDebug;
64import android.view.ViewManager;
65import 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) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 synchronized (mPackages) {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700182 // Resources is app scale dependent.
183 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700184 if (false) {
185 Log.w(TAG, "getTopLevelResources: " + resDir + " / "
186 + compInfo.applicationScale);
187 }
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700188 WeakReference<Resources> wr = mActiveResources.get(key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 Resources r = wr != null ? wr.get() : null;
190 if (r != null && r.getAssets().isUpToDate()) {
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700191 if (false) {
192 Log.w(TAG, "Returning cached resources " + r + " " + resDir
193 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 return r;
196 }
197
198 //if (r != null) {
199 // Log.w(TAG, "Throwing away out-of-date resources!!!! "
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700200 // + r + " " + resDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 //}
202
203 AssetManager assets = new AssetManager();
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700204 if (assets.addAssetPath(resDir) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 return null;
206 }
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700207
208 //Log.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700209 DisplayMetrics metrics = getDisplayMetricsLocked(false);
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700210 r = new Resources(assets, metrics, getConfiguration(), compInfo);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700211 if (false) {
212 Log.i(TAG, "Created app resources " + resDir + " " + r + ": "
213 + r.getConfiguration() + " appScale="
214 + r.getCompatibilityInfo().applicationScale);
215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 // XXX need to remove entries when weak references go away
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700217 mActiveResources.put(key, new WeakReference<Resources>(r));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 return r;
219 }
220 }
221
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700222 /**
223 * Creates the top level resources for the given package.
224 */
225 Resources getTopLevelResources(String resDir, PackageInfo pkgInfo) {
226 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
227 }
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 final Handler getHandler() {
230 return mH;
231 }
232
233 public final static class PackageInfo {
234
235 private final ActivityThread mActivityThread;
236 private final ApplicationInfo mApplicationInfo;
237 private final String mPackageName;
238 private final String mAppDir;
239 private final String mResDir;
240 private final String[] mSharedLibraries;
241 private final String mDataDir;
242 private final File mDataDirFile;
243 private final ClassLoader mBaseClassLoader;
244 private final boolean mSecurityViolation;
245 private final boolean mIncludeCode;
246 private Resources mResources;
247 private ClassLoader mClassLoader;
248 private Application mApplication;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700249 private CompatibilityInfo mCompatibilityInfo;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mReceivers
252 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
253 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mUnregisteredReceivers
254 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
255 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mServices
256 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
257 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mUnboundServices
258 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
259
260 int mClientCount = 0;
261
262 public PackageInfo(ActivityThread activityThread, ApplicationInfo aInfo,
263 ActivityThread mainThread, ClassLoader baseLoader,
264 boolean securityViolation, boolean includeCode) {
265 mActivityThread = activityThread;
266 mApplicationInfo = aInfo;
267 mPackageName = aInfo.packageName;
268 mAppDir = aInfo.sourceDir;
269 mResDir = aInfo.uid == Process.myUid() ? aInfo.sourceDir
270 : aInfo.publicSourceDir;
271 mSharedLibraries = aInfo.sharedLibraryFiles;
272 mDataDir = aInfo.dataDir;
273 mDataDirFile = mDataDir != null ? new File(mDataDir) : null;
274 mBaseClassLoader = baseLoader;
275 mSecurityViolation = securityViolation;
276 mIncludeCode = includeCode;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700277 mCompatibilityInfo = new CompatibilityInfo(aInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278
279 if (mAppDir == null) {
280 if (mSystemContext == null) {
281 mSystemContext =
282 ApplicationContext.createSystemContext(mainThread);
283 mSystemContext.getResources().updateConfiguration(
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700284 mainThread.getConfiguration(),
285 mainThread.getDisplayMetricsLocked(false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 //Log.i(TAG, "Created system resources "
287 // + mSystemContext.getResources() + ": "
288 // + mSystemContext.getResources().getConfiguration());
289 }
290 mClassLoader = mSystemContext.getClassLoader();
291 mResources = mSystemContext.getResources();
292 }
293 }
294
295 public PackageInfo(ActivityThread activityThread, String name,
Mike Cleron432b7132009-09-24 15:28:29 -0700296 Context systemContext, ApplicationInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 mActivityThread = activityThread;
Mike Cleron432b7132009-09-24 15:28:29 -0700298 mApplicationInfo = info != null ? info : new ApplicationInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 mApplicationInfo.packageName = name;
300 mPackageName = name;
301 mAppDir = null;
302 mResDir = null;
303 mSharedLibraries = null;
304 mDataDir = null;
305 mDataDirFile = null;
306 mBaseClassLoader = null;
307 mSecurityViolation = false;
308 mIncludeCode = true;
309 mClassLoader = systemContext.getClassLoader();
310 mResources = systemContext.getResources();
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700311 mCompatibilityInfo = new CompatibilityInfo(mApplicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 }
313
314 public String getPackageName() {
315 return mPackageName;
316 }
317
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700318 public ApplicationInfo getApplicationInfo() {
319 return mApplicationInfo;
320 }
Bob Leee5408332009-09-04 18:31:17 -0700321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 public boolean isSecurityViolation() {
323 return mSecurityViolation;
324 }
325
326 /**
327 * Gets the array of shared libraries that are listed as
328 * used by the given package.
Bob Leee5408332009-09-04 18:31:17 -0700329 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 * @param packageName the name of the package (note: not its
331 * file name)
332 * @return null-ok; the array of shared libraries, each one
333 * a fully-qualified path
334 */
335 private static String[] getLibrariesFor(String packageName) {
336 ApplicationInfo ai = null;
337 try {
338 ai = getPackageManager().getApplicationInfo(packageName,
339 PackageManager.GET_SHARED_LIBRARY_FILES);
340 } catch (RemoteException e) {
341 throw new AssertionError(e);
342 }
343
344 if (ai == null) {
345 return null;
346 }
347
348 return ai.sharedLibraryFiles;
349 }
350
351 /**
352 * Combines two arrays (of library names) such that they are
353 * concatenated in order but are devoid of duplicates. The
354 * result is a single string with the names of the libraries
355 * separated by colons, or <code>null</code> if both lists
356 * were <code>null</code> or empty.
Bob Leee5408332009-09-04 18:31:17 -0700357 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 * @param list1 null-ok; the first list
359 * @param list2 null-ok; the second list
360 * @return null-ok; the combination
361 */
362 private static String combineLibs(String[] list1, String[] list2) {
363 StringBuilder result = new StringBuilder(300);
364 boolean first = true;
365
366 if (list1 != null) {
367 for (String s : list1) {
368 if (first) {
369 first = false;
370 } else {
371 result.append(':');
372 }
373 result.append(s);
374 }
375 }
376
377 // Only need to check for duplicates if list1 was non-empty.
378 boolean dupCheck = !first;
379
380 if (list2 != null) {
381 for (String s : list2) {
382 if (dupCheck && ArrayUtils.contains(list1, s)) {
383 continue;
384 }
Bob Leee5408332009-09-04 18:31:17 -0700385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 if (first) {
387 first = false;
388 } else {
389 result.append(':');
390 }
391 result.append(s);
392 }
393 }
394
395 return result.toString();
396 }
Bob Leee5408332009-09-04 18:31:17 -0700397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 public ClassLoader getClassLoader() {
399 synchronized (this) {
400 if (mClassLoader != null) {
401 return mClassLoader;
402 }
403
404 if (mIncludeCode && !mPackageName.equals("android")) {
405 String zip = mAppDir;
406
407 /*
408 * The following is a bit of a hack to inject
409 * instrumentation into the system: If the app
410 * being started matches one of the instrumentation names,
411 * then we combine both the "instrumentation" and
412 * "instrumented" app into the path, along with the
413 * concatenation of both apps' shared library lists.
414 */
415
416 String instrumentationAppDir =
417 mActivityThread.mInstrumentationAppDir;
418 String instrumentationAppPackage =
419 mActivityThread.mInstrumentationAppPackage;
420 String instrumentedAppDir =
421 mActivityThread.mInstrumentedAppDir;
422 String[] instrumentationLibs = null;
423
424 if (mAppDir.equals(instrumentationAppDir)
425 || mAppDir.equals(instrumentedAppDir)) {
426 zip = instrumentationAppDir + ":" + instrumentedAppDir;
427 if (! instrumentedAppDir.equals(instrumentationAppDir)) {
428 instrumentationLibs =
429 getLibrariesFor(instrumentationAppPackage);
430 }
431 }
432
433 if ((mSharedLibraries != null) ||
434 (instrumentationLibs != null)) {
Bob Leee5408332009-09-04 18:31:17 -0700435 zip =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 combineLibs(mSharedLibraries, instrumentationLibs)
437 + ':' + zip;
438 }
439
440 /*
441 * With all the combination done (if necessary, actually
442 * create the class loader.
443 */
444
445 if (localLOGV) Log.v(TAG, "Class path: " + zip);
446
447 mClassLoader =
448 ApplicationLoaders.getDefault().getClassLoader(
449 zip, mDataDir, mBaseClassLoader);
450 } else {
451 if (mBaseClassLoader == null) {
452 mClassLoader = ClassLoader.getSystemClassLoader();
453 } else {
454 mClassLoader = mBaseClassLoader;
455 }
456 }
457 return mClassLoader;
458 }
459 }
460
461 public String getAppDir() {
462 return mAppDir;
463 }
464
465 public String getResDir() {
466 return mResDir;
467 }
468
469 public String getDataDir() {
470 return mDataDir;
471 }
472
473 public File getDataDirFile() {
474 return mDataDirFile;
475 }
476
477 public AssetManager getAssets(ActivityThread mainThread) {
478 return getResources(mainThread).getAssets();
479 }
480
481 public Resources getResources(ActivityThread mainThread) {
482 if (mResources == null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700483 mResources = mainThread.getTopLevelResources(mResDir, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 }
485 return mResources;
486 }
487
Dianne Hackborn0be1f782009-11-09 12:30:12 -0800488 public Application makeApplication(boolean forceDefaultAppClass,
489 Instrumentation instrumentation) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 if (mApplication != null) {
491 return mApplication;
492 }
Bob Leee5408332009-09-04 18:31:17 -0700493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 Application app = null;
Bob Leee5408332009-09-04 18:31:17 -0700495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 String appClass = mApplicationInfo.className;
Christopher Tate181fafa2009-05-14 11:12:14 -0700497 if (forceDefaultAppClass || (appClass == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 appClass = "android.app.Application";
499 }
500
501 try {
502 java.lang.ClassLoader cl = getClassLoader();
503 ApplicationContext appContext = new ApplicationContext();
504 appContext.init(this, null, mActivityThread);
505 app = mActivityThread.mInstrumentation.newApplication(
506 cl, appClass, appContext);
507 appContext.setOuterContext(app);
508 } catch (Exception e) {
509 if (!mActivityThread.mInstrumentation.onException(app, e)) {
510 throw new RuntimeException(
511 "Unable to instantiate application " + appClass
512 + ": " + e.toString(), e);
513 }
514 }
515 mActivityThread.mAllApplications.add(app);
Dianne Hackborn0be1f782009-11-09 12:30:12 -0800516 mApplication = app;
517
518 if (instrumentation != null) {
519 try {
520 instrumentation.callApplicationOnCreate(app);
521 } catch (Exception e) {
522 if (!instrumentation.onException(app, e)) {
523 throw new RuntimeException(
524 "Unable to create application " + app.getClass().getName()
525 + ": " + e.toString(), e);
526 }
527 }
528 }
529
530 return app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 }
Bob Leee5408332009-09-04 18:31:17 -0700532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 public void removeContextRegistrations(Context context,
534 String who, String what) {
535 HashMap<BroadcastReceiver, ReceiverDispatcher> rmap =
536 mReceivers.remove(context);
537 if (rmap != null) {
538 Iterator<ReceiverDispatcher> it = rmap.values().iterator();
539 while (it.hasNext()) {
540 ReceiverDispatcher rd = it.next();
541 IntentReceiverLeaked leak = new IntentReceiverLeaked(
542 what + " " + who + " has leaked IntentReceiver "
543 + rd.getIntentReceiver() + " that was " +
544 "originally registered here. Are you missing a " +
545 "call to unregisterReceiver()?");
546 leak.setStackTrace(rd.getLocation().getStackTrace());
547 Log.e(TAG, leak.getMessage(), leak);
548 try {
549 ActivityManagerNative.getDefault().unregisterReceiver(
550 rd.getIIntentReceiver());
551 } catch (RemoteException e) {
552 // system crashed, nothing we can do
553 }
554 }
555 }
556 mUnregisteredReceivers.remove(context);
557 //Log.i(TAG, "Receiver registrations: " + mReceivers);
558 HashMap<ServiceConnection, ServiceDispatcher> smap =
559 mServices.remove(context);
560 if (smap != null) {
561 Iterator<ServiceDispatcher> it = smap.values().iterator();
562 while (it.hasNext()) {
563 ServiceDispatcher sd = it.next();
564 ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
565 what + " " + who + " has leaked ServiceConnection "
566 + sd.getServiceConnection() + " that was originally bound here");
567 leak.setStackTrace(sd.getLocation().getStackTrace());
568 Log.e(TAG, leak.getMessage(), leak);
569 try {
570 ActivityManagerNative.getDefault().unbindService(
571 sd.getIServiceConnection());
572 } catch (RemoteException e) {
573 // system crashed, nothing we can do
574 }
575 sd.doForget();
576 }
577 }
578 mUnboundServices.remove(context);
579 //Log.i(TAG, "Service registrations: " + mServices);
580 }
581
582 public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,
583 Context context, Handler handler,
584 Instrumentation instrumentation, boolean registered) {
585 synchronized (mReceivers) {
586 ReceiverDispatcher rd = null;
587 HashMap<BroadcastReceiver, ReceiverDispatcher> map = null;
588 if (registered) {
589 map = mReceivers.get(context);
590 if (map != null) {
591 rd = map.get(r);
592 }
593 }
594 if (rd == null) {
595 rd = new ReceiverDispatcher(r, context, handler,
596 instrumentation, registered);
597 if (registered) {
598 if (map == null) {
599 map = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
600 mReceivers.put(context, map);
601 }
602 map.put(r, rd);
603 }
604 } else {
605 rd.validate(context, handler);
606 }
607 return rd.getIIntentReceiver();
608 }
609 }
610
611 public IIntentReceiver forgetReceiverDispatcher(Context context,
612 BroadcastReceiver r) {
613 synchronized (mReceivers) {
614 HashMap<BroadcastReceiver, ReceiverDispatcher> map = mReceivers.get(context);
615 ReceiverDispatcher rd = null;
616 if (map != null) {
617 rd = map.get(r);
618 if (rd != null) {
619 map.remove(r);
620 if (map.size() == 0) {
621 mReceivers.remove(context);
622 }
623 if (r.getDebugUnregister()) {
624 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
625 = mUnregisteredReceivers.get(context);
626 if (holder == null) {
627 holder = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
628 mUnregisteredReceivers.put(context, holder);
629 }
630 RuntimeException ex = new IllegalArgumentException(
631 "Originally unregistered here:");
632 ex.fillInStackTrace();
633 rd.setUnregisterLocation(ex);
634 holder.put(r, rd);
635 }
636 return rd.getIIntentReceiver();
637 }
638 }
639 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
640 = mUnregisteredReceivers.get(context);
641 if (holder != null) {
642 rd = holder.get(r);
643 if (rd != null) {
644 RuntimeException ex = rd.getUnregisterLocation();
645 throw new IllegalArgumentException(
646 "Unregistering Receiver " + r
647 + " that was already unregistered", ex);
648 }
649 }
650 if (context == null) {
651 throw new IllegalStateException("Unbinding Receiver " + r
652 + " from Context that is no longer in use: " + context);
653 } else {
654 throw new IllegalArgumentException("Receiver not registered: " + r);
655 }
656
657 }
658 }
659
660 static final class ReceiverDispatcher {
661
662 final static class InnerReceiver extends IIntentReceiver.Stub {
663 final WeakReference<ReceiverDispatcher> mDispatcher;
664 final ReceiverDispatcher mStrongRef;
Bob Leee5408332009-09-04 18:31:17 -0700665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 InnerReceiver(ReceiverDispatcher rd, boolean strong) {
667 mDispatcher = new WeakReference<ReceiverDispatcher>(rd);
668 mStrongRef = strong ? rd : null;
669 }
670 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700671 String data, Bundle extras, boolean ordered, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 ReceiverDispatcher rd = mDispatcher.get();
673 if (DEBUG_BROADCAST) {
674 int seq = intent.getIntExtra("seq", -1);
675 Log.i(TAG, "Receiving broadcast " + intent.getAction() + " seq=" + seq
676 + " to " + rd);
677 }
678 if (rd != null) {
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700679 rd.performReceive(intent, resultCode, data, extras,
680 ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
682 }
683 }
Bob Leee5408332009-09-04 18:31:17 -0700684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 final IIntentReceiver.Stub mIIntentReceiver;
686 final BroadcastReceiver mReceiver;
687 final Context mContext;
688 final Handler mActivityThread;
689 final Instrumentation mInstrumentation;
690 final boolean mRegistered;
691 final IntentReceiverLeaked mLocation;
692 RuntimeException mUnregisterLocation;
693
694 final class Args implements Runnable {
695 private Intent mCurIntent;
696 private int mCurCode;
697 private String mCurData;
698 private Bundle mCurMap;
699 private boolean mCurOrdered;
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700700 private boolean mCurSticky;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701
702 public void run() {
703 BroadcastReceiver receiver = mReceiver;
704 if (DEBUG_BROADCAST) {
705 int seq = mCurIntent.getIntExtra("seq", -1);
706 Log.i(TAG, "Dispathing broadcast " + mCurIntent.getAction() + " seq=" + seq
707 + " to " + mReceiver);
708 }
709 if (receiver == null) {
710 return;
711 }
712
713 IActivityManager mgr = ActivityManagerNative.getDefault();
714 Intent intent = mCurIntent;
715 mCurIntent = null;
716 try {
717 ClassLoader cl = mReceiver.getClass().getClassLoader();
718 intent.setExtrasClassLoader(cl);
719 if (mCurMap != null) {
720 mCurMap.setClassLoader(cl);
721 }
722 receiver.setOrderedHint(true);
723 receiver.setResult(mCurCode, mCurData, mCurMap);
724 receiver.clearAbortBroadcast();
725 receiver.setOrderedHint(mCurOrdered);
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700726 receiver.setInitialStickyHint(mCurSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 receiver.onReceive(mContext, intent);
728 } catch (Exception e) {
729 if (mRegistered && mCurOrdered) {
730 try {
731 mgr.finishReceiver(mIIntentReceiver,
732 mCurCode, mCurData, mCurMap, false);
733 } catch (RemoteException ex) {
734 }
735 }
736 if (mInstrumentation == null ||
737 !mInstrumentation.onException(mReceiver, e)) {
738 throw new RuntimeException(
739 "Error receiving broadcast " + intent
740 + " in " + mReceiver, e);
741 }
742 }
743 if (mRegistered && mCurOrdered) {
744 try {
745 mgr.finishReceiver(mIIntentReceiver,
746 receiver.getResultCode(),
747 receiver.getResultData(),
748 receiver.getResultExtras(false),
749 receiver.getAbortBroadcast());
750 } catch (RemoteException ex) {
751 }
752 }
753 }
754 }
755
756 ReceiverDispatcher(BroadcastReceiver receiver, Context context,
757 Handler activityThread, Instrumentation instrumentation,
758 boolean registered) {
759 if (activityThread == null) {
760 throw new NullPointerException("Handler must not be null");
761 }
762
763 mIIntentReceiver = new InnerReceiver(this, !registered);
764 mReceiver = receiver;
765 mContext = context;
766 mActivityThread = activityThread;
767 mInstrumentation = instrumentation;
768 mRegistered = registered;
769 mLocation = new IntentReceiverLeaked(null);
770 mLocation.fillInStackTrace();
771 }
772
773 void validate(Context context, Handler activityThread) {
774 if (mContext != context) {
775 throw new IllegalStateException(
776 "Receiver " + mReceiver +
777 " registered with differing Context (was " +
778 mContext + " now " + context + ")");
779 }
780 if (mActivityThread != activityThread) {
781 throw new IllegalStateException(
782 "Receiver " + mReceiver +
783 " registered with differing handler (was " +
784 mActivityThread + " now " + activityThread + ")");
785 }
786 }
787
788 IntentReceiverLeaked getLocation() {
789 return mLocation;
790 }
791
792 BroadcastReceiver getIntentReceiver() {
793 return mReceiver;
794 }
Bob Leee5408332009-09-04 18:31:17 -0700795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 IIntentReceiver getIIntentReceiver() {
797 return mIIntentReceiver;
798 }
799
800 void setUnregisterLocation(RuntimeException ex) {
801 mUnregisterLocation = ex;
802 }
803
804 RuntimeException getUnregisterLocation() {
805 return mUnregisterLocation;
806 }
807
808 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700809 String data, Bundle extras, boolean ordered, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 if (DEBUG_BROADCAST) {
811 int seq = intent.getIntExtra("seq", -1);
812 Log.i(TAG, "Enqueueing broadcast " + intent.getAction() + " seq=" + seq
813 + " to " + mReceiver);
814 }
815 Args args = new Args();
816 args.mCurIntent = intent;
817 args.mCurCode = resultCode;
818 args.mCurData = data;
819 args.mCurMap = extras;
820 args.mCurOrdered = ordered;
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700821 args.mCurSticky = sticky;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 if (!mActivityThread.post(args)) {
823 if (mRegistered) {
824 IActivityManager mgr = ActivityManagerNative.getDefault();
825 try {
826 mgr.finishReceiver(mIIntentReceiver, args.mCurCode,
827 args.mCurData, args.mCurMap, false);
828 } catch (RemoteException ex) {
829 }
830 }
831 }
832 }
833
834 }
835
836 public final IServiceConnection getServiceDispatcher(ServiceConnection c,
837 Context context, Handler handler, int flags) {
838 synchronized (mServices) {
839 ServiceDispatcher sd = null;
840 HashMap<ServiceConnection, ServiceDispatcher> map = mServices.get(context);
841 if (map != null) {
842 sd = map.get(c);
843 }
844 if (sd == null) {
845 sd = new ServiceDispatcher(c, context, handler, flags);
846 if (map == null) {
847 map = new HashMap<ServiceConnection, ServiceDispatcher>();
848 mServices.put(context, map);
849 }
850 map.put(c, sd);
851 } else {
852 sd.validate(context, handler);
853 }
854 return sd.getIServiceConnection();
855 }
856 }
857
858 public final IServiceConnection forgetServiceDispatcher(Context context,
859 ServiceConnection c) {
860 synchronized (mServices) {
861 HashMap<ServiceConnection, ServiceDispatcher> map
862 = mServices.get(context);
863 ServiceDispatcher sd = null;
864 if (map != null) {
865 sd = map.get(c);
866 if (sd != null) {
867 map.remove(c);
868 sd.doForget();
869 if (map.size() == 0) {
870 mServices.remove(context);
871 }
872 if ((sd.getFlags()&Context.BIND_DEBUG_UNBIND) != 0) {
873 HashMap<ServiceConnection, ServiceDispatcher> holder
874 = mUnboundServices.get(context);
875 if (holder == null) {
876 holder = new HashMap<ServiceConnection, ServiceDispatcher>();
877 mUnboundServices.put(context, holder);
878 }
879 RuntimeException ex = new IllegalArgumentException(
880 "Originally unbound here:");
881 ex.fillInStackTrace();
882 sd.setUnbindLocation(ex);
883 holder.put(c, sd);
884 }
885 return sd.getIServiceConnection();
886 }
887 }
888 HashMap<ServiceConnection, ServiceDispatcher> holder
889 = mUnboundServices.get(context);
890 if (holder != null) {
891 sd = holder.get(c);
892 if (sd != null) {
893 RuntimeException ex = sd.getUnbindLocation();
894 throw new IllegalArgumentException(
895 "Unbinding Service " + c
896 + " that was already unbound", ex);
897 }
898 }
899 if (context == null) {
900 throw new IllegalStateException("Unbinding Service " + c
901 + " from Context that is no longer in use: " + context);
902 } else {
903 throw new IllegalArgumentException("Service not registered: " + c);
904 }
905 }
906 }
907
908 static final class ServiceDispatcher {
909 private final InnerConnection mIServiceConnection;
910 private final ServiceConnection mConnection;
911 private final Context mContext;
912 private final Handler mActivityThread;
913 private final ServiceConnectionLeaked mLocation;
914 private final int mFlags;
915
916 private RuntimeException mUnbindLocation;
917
918 private boolean mDied;
919
920 private static class ConnectionInfo {
921 IBinder binder;
922 IBinder.DeathRecipient deathMonitor;
923 }
924
925 private static class InnerConnection extends IServiceConnection.Stub {
926 final WeakReference<ServiceDispatcher> mDispatcher;
Bob Leee5408332009-09-04 18:31:17 -0700927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 InnerConnection(ServiceDispatcher sd) {
929 mDispatcher = new WeakReference<ServiceDispatcher>(sd);
930 }
931
932 public void connected(ComponentName name, IBinder service) throws RemoteException {
933 ServiceDispatcher sd = mDispatcher.get();
934 if (sd != null) {
935 sd.connected(name, service);
936 }
937 }
938 }
Bob Leee5408332009-09-04 18:31:17 -0700939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 private final HashMap<ComponentName, ConnectionInfo> mActiveConnections
941 = new HashMap<ComponentName, ConnectionInfo>();
942
943 ServiceDispatcher(ServiceConnection conn,
944 Context context, Handler activityThread, int flags) {
945 mIServiceConnection = new InnerConnection(this);
946 mConnection = conn;
947 mContext = context;
948 mActivityThread = activityThread;
949 mLocation = new ServiceConnectionLeaked(null);
950 mLocation.fillInStackTrace();
951 mFlags = flags;
952 }
953
954 void validate(Context context, Handler activityThread) {
955 if (mContext != context) {
956 throw new RuntimeException(
957 "ServiceConnection " + mConnection +
958 " registered with differing Context (was " +
959 mContext + " now " + context + ")");
960 }
961 if (mActivityThread != activityThread) {
962 throw new RuntimeException(
963 "ServiceConnection " + mConnection +
964 " registered with differing handler (was " +
965 mActivityThread + " now " + activityThread + ")");
966 }
967 }
968
969 void doForget() {
970 synchronized(this) {
971 Iterator<ConnectionInfo> it = mActiveConnections.values().iterator();
972 while (it.hasNext()) {
973 ConnectionInfo ci = it.next();
974 ci.binder.unlinkToDeath(ci.deathMonitor, 0);
975 }
976 mActiveConnections.clear();
977 }
978 }
979
980 ServiceConnectionLeaked getLocation() {
981 return mLocation;
982 }
983
984 ServiceConnection getServiceConnection() {
985 return mConnection;
986 }
987
988 IServiceConnection getIServiceConnection() {
989 return mIServiceConnection;
990 }
Bob Leee5408332009-09-04 18:31:17 -0700991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 int getFlags() {
993 return mFlags;
994 }
995
996 void setUnbindLocation(RuntimeException ex) {
997 mUnbindLocation = ex;
998 }
999
1000 RuntimeException getUnbindLocation() {
1001 return mUnbindLocation;
1002 }
1003
1004 public void connected(ComponentName name, IBinder service) {
1005 if (mActivityThread != null) {
1006 mActivityThread.post(new RunConnection(name, service, 0));
1007 } else {
1008 doConnected(name, service);
1009 }
1010 }
1011
1012 public void death(ComponentName name, IBinder service) {
1013 ConnectionInfo old;
1014
1015 synchronized (this) {
1016 mDied = true;
1017 old = mActiveConnections.remove(name);
1018 if (old == null || old.binder != service) {
1019 // Death for someone different than who we last
1020 // reported... just ignore it.
1021 return;
1022 }
1023 old.binder.unlinkToDeath(old.deathMonitor, 0);
1024 }
1025
1026 if (mActivityThread != null) {
1027 mActivityThread.post(new RunConnection(name, service, 1));
1028 } else {
1029 doDeath(name, service);
1030 }
1031 }
1032
1033 public void doConnected(ComponentName name, IBinder service) {
1034 ConnectionInfo old;
1035 ConnectionInfo info;
1036
1037 synchronized (this) {
1038 old = mActiveConnections.get(name);
1039 if (old != null && old.binder == service) {
1040 // Huh, already have this one. Oh well!
1041 return;
1042 }
1043
1044 if (service != null) {
1045 // A new service is being connected... set it all up.
1046 mDied = false;
1047 info = new ConnectionInfo();
1048 info.binder = service;
1049 info.deathMonitor = new DeathMonitor(name, service);
1050 try {
1051 service.linkToDeath(info.deathMonitor, 0);
1052 mActiveConnections.put(name, info);
1053 } catch (RemoteException e) {
1054 // This service was dead before we got it... just
1055 // don't do anything with it.
1056 mActiveConnections.remove(name);
1057 return;
1058 }
1059
1060 } else {
1061 // The named service is being disconnected... clean up.
1062 mActiveConnections.remove(name);
1063 }
1064
1065 if (old != null) {
1066 old.binder.unlinkToDeath(old.deathMonitor, 0);
1067 }
1068 }
1069
1070 // If there was an old service, it is not disconnected.
1071 if (old != null) {
1072 mConnection.onServiceDisconnected(name);
1073 }
1074 // If there is a new service, it is now connected.
1075 if (service != null) {
1076 mConnection.onServiceConnected(name, service);
1077 }
1078 }
1079
1080 public void doDeath(ComponentName name, IBinder service) {
1081 mConnection.onServiceDisconnected(name);
1082 }
1083
1084 private final class RunConnection implements Runnable {
1085 RunConnection(ComponentName name, IBinder service, int command) {
1086 mName = name;
1087 mService = service;
1088 mCommand = command;
1089 }
1090
1091 public void run() {
1092 if (mCommand == 0) {
1093 doConnected(mName, mService);
1094 } else if (mCommand == 1) {
1095 doDeath(mName, mService);
1096 }
1097 }
1098
1099 final ComponentName mName;
1100 final IBinder mService;
1101 final int mCommand;
1102 }
1103
1104 private final class DeathMonitor implements IBinder.DeathRecipient
1105 {
1106 DeathMonitor(ComponentName name, IBinder service) {
1107 mName = name;
1108 mService = service;
1109 }
1110
1111 public void binderDied() {
1112 death(mName, mService);
1113 }
1114
1115 final ComponentName mName;
1116 final IBinder mService;
1117 }
1118 }
1119 }
1120
1121 private static ApplicationContext mSystemContext = null;
1122
1123 private static final class ActivityRecord {
1124 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001125 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 Intent intent;
1127 Bundle state;
1128 Activity activity;
1129 Window window;
1130 Activity parent;
1131 String embeddedID;
1132 Object lastNonConfigurationInstance;
1133 HashMap<String,Object> lastNonConfigurationChildInstances;
1134 boolean paused;
1135 boolean stopped;
1136 boolean hideForNow;
1137 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -07001138 Configuration createdConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 ActivityRecord nextIdle;
1140
1141 ActivityInfo activityInfo;
1142 PackageInfo packageInfo;
1143
1144 List<ResultInfo> pendingResults;
1145 List<Intent> pendingIntents;
1146
1147 boolean startsNotResumed;
1148 boolean isForward;
1149
1150 ActivityRecord() {
1151 parent = null;
1152 embeddedID = null;
1153 paused = false;
1154 stopped = false;
1155 hideForNow = false;
1156 nextIdle = null;
1157 }
1158
1159 public String toString() {
1160 ComponentName componentName = intent.getComponent();
1161 return "ActivityRecord{"
1162 + Integer.toHexString(System.identityHashCode(this))
1163 + " token=" + token + " " + (componentName == null
1164 ? "no component name" : componentName.toShortString())
1165 + "}";
1166 }
1167 }
1168
1169 private final class ProviderRecord implements IBinder.DeathRecipient {
1170 final String mName;
1171 final IContentProvider mProvider;
1172 final ContentProvider mLocalProvider;
1173
1174 ProviderRecord(String name, IContentProvider provider,
1175 ContentProvider localProvider) {
1176 mName = name;
1177 mProvider = provider;
1178 mLocalProvider = localProvider;
1179 }
1180
1181 public void binderDied() {
1182 removeDeadProvider(mName, mProvider);
1183 }
1184 }
1185
1186 private static final class NewIntentData {
1187 List<Intent> intents;
1188 IBinder token;
1189 public String toString() {
1190 return "NewIntentData{intents=" + intents + " token=" + token + "}";
1191 }
1192 }
1193
1194 private static final class ReceiverData {
1195 Intent intent;
1196 ActivityInfo info;
1197 int resultCode;
1198 String resultData;
1199 Bundle resultExtras;
1200 boolean sync;
1201 boolean resultAbort;
1202 public String toString() {
1203 return "ReceiverData{intent=" + intent + " packageName=" +
1204 info.packageName + " resultCode=" + resultCode
1205 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
1206 }
1207 }
1208
Christopher Tate181fafa2009-05-14 11:12:14 -07001209 private static final class CreateBackupAgentData {
1210 ApplicationInfo appInfo;
1211 int backupMode;
1212 public String toString() {
1213 return "CreateBackupAgentData{appInfo=" + appInfo
1214 + " backupAgent=" + appInfo.backupAgentName
1215 + " mode=" + backupMode + "}";
1216 }
1217 }
Bob Leee5408332009-09-04 18:31:17 -07001218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 private static final class CreateServiceData {
1220 IBinder token;
1221 ServiceInfo info;
1222 Intent intent;
1223 public String toString() {
1224 return "CreateServiceData{token=" + token + " className="
1225 + info.name + " packageName=" + info.packageName
1226 + " intent=" + intent + "}";
1227 }
1228 }
1229
1230 private static final class BindServiceData {
1231 IBinder token;
1232 Intent intent;
1233 boolean rebind;
1234 public String toString() {
1235 return "BindServiceData{token=" + token + " intent=" + intent + "}";
1236 }
1237 }
1238
1239 private static final class ServiceArgsData {
1240 IBinder token;
1241 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001242 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 Intent args;
1244 public String toString() {
1245 return "ServiceArgsData{token=" + token + " startId=" + startId
1246 + " args=" + args + "}";
1247 }
1248 }
1249
1250 private static final class AppBindData {
1251 PackageInfo info;
1252 String processName;
1253 ApplicationInfo appInfo;
1254 List<ProviderInfo> providers;
1255 ComponentName instrumentationName;
1256 String profileFile;
1257 Bundle instrumentationArgs;
1258 IInstrumentationWatcher instrumentationWatcher;
1259 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001260 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 Configuration config;
1262 boolean handlingProfiling;
1263 public String toString() {
1264 return "AppBindData{appInfo=" + appInfo + "}";
1265 }
1266 }
1267
1268 private static final class DumpServiceInfo {
1269 FileDescriptor fd;
1270 IBinder service;
1271 String[] args;
1272 boolean dumped;
1273 }
1274
1275 private static final class ResultData {
1276 IBinder token;
1277 List<ResultInfo> results;
1278 public String toString() {
1279 return "ResultData{token=" + token + " results" + results + "}";
1280 }
1281 }
1282
1283 private static final class ContextCleanupInfo {
1284 ApplicationContext context;
1285 String what;
1286 String who;
1287 }
1288
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001289 private static final class ProfilerControlData {
1290 String path;
1291 ParcelFileDescriptor fd;
1292 }
1293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 private final class ApplicationThread extends ApplicationThreadNative {
1295 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
1296 private static final String ONE_COUNT_COLUMN = "%17s %8d";
1297 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Bob Leee5408332009-09-04 18:31:17 -07001298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 // Formatting for checkin service - update version if row format changes
1300 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -07001301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 public final void schedulePauseActivity(IBinder token, boolean finished,
1303 boolean userLeaving, int configChanges) {
1304 queueOrSendMessage(
1305 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
1306 token,
1307 (userLeaving ? 1 : 0),
1308 configChanges);
1309 }
1310
1311 public final void scheduleStopActivity(IBinder token, boolean showWindow,
1312 int configChanges) {
1313 queueOrSendMessage(
1314 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
1315 token, 0, configChanges);
1316 }
1317
1318 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
1319 queueOrSendMessage(
1320 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
1321 token);
1322 }
1323
1324 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
1325 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
1326 }
1327
1328 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
1329 ResultData res = new ResultData();
1330 res.token = token;
1331 res.results = results;
1332 queueOrSendMessage(H.SEND_RESULT, res);
1333 }
1334
1335 // we use token to identify this activity without having to send the
1336 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001337 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
1339 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
1340 ActivityRecord r = new ActivityRecord();
1341
1342 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001343 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 r.intent = intent;
1345 r.activityInfo = info;
1346 r.state = state;
1347
1348 r.pendingResults = pendingResults;
1349 r.pendingIntents = pendingNewIntents;
1350
1351 r.startsNotResumed = notResumed;
1352 r.isForward = isForward;
1353
1354 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
1355 }
1356
1357 public final void scheduleRelaunchActivity(IBinder token,
1358 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
1359 int configChanges, boolean notResumed) {
1360 ActivityRecord r = new ActivityRecord();
1361
1362 r.token = token;
1363 r.pendingResults = pendingResults;
1364 r.pendingIntents = pendingNewIntents;
1365 r.startsNotResumed = notResumed;
1366
1367 synchronized (mRelaunchingActivities) {
1368 mRelaunchingActivities.add(r);
1369 }
Bob Leee5408332009-09-04 18:31:17 -07001370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
1372 }
1373
1374 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
1375 NewIntentData data = new NewIntentData();
1376 data.intents = intents;
1377 data.token = token;
1378
1379 queueOrSendMessage(H.NEW_INTENT, data);
1380 }
1381
1382 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
1383 int configChanges) {
1384 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
1385 configChanges);
1386 }
1387
1388 public final void scheduleReceiver(Intent intent, ActivityInfo info,
1389 int resultCode, String data, Bundle extras, boolean sync) {
1390 ReceiverData r = new ReceiverData();
1391
1392 r.intent = intent;
1393 r.info = info;
1394 r.resultCode = resultCode;
1395 r.resultData = data;
1396 r.resultExtras = extras;
1397 r.sync = sync;
1398
1399 queueOrSendMessage(H.RECEIVER, r);
1400 }
1401
Christopher Tate181fafa2009-05-14 11:12:14 -07001402 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
1403 CreateBackupAgentData d = new CreateBackupAgentData();
1404 d.appInfo = app;
1405 d.backupMode = backupMode;
1406
1407 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
1408 }
1409
1410 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
1411 CreateBackupAgentData d = new CreateBackupAgentData();
1412 d.appInfo = app;
1413
1414 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
1415 }
1416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 public final void scheduleCreateService(IBinder token,
1418 ServiceInfo info) {
1419 CreateServiceData s = new CreateServiceData();
1420 s.token = token;
1421 s.info = info;
1422
1423 queueOrSendMessage(H.CREATE_SERVICE, s);
1424 }
1425
1426 public final void scheduleBindService(IBinder token, Intent intent,
1427 boolean rebind) {
1428 BindServiceData s = new BindServiceData();
1429 s.token = token;
1430 s.intent = intent;
1431 s.rebind = rebind;
1432
1433 queueOrSendMessage(H.BIND_SERVICE, s);
1434 }
1435
1436 public final void scheduleUnbindService(IBinder token, Intent intent) {
1437 BindServiceData s = new BindServiceData();
1438 s.token = token;
1439 s.intent = intent;
1440
1441 queueOrSendMessage(H.UNBIND_SERVICE, s);
1442 }
1443
1444 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001445 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 ServiceArgsData s = new ServiceArgsData();
1447 s.token = token;
1448 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001449 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 s.args = args;
1451
1452 queueOrSendMessage(H.SERVICE_ARGS, s);
1453 }
1454
1455 public final void scheduleStopService(IBinder token) {
1456 queueOrSendMessage(H.STOP_SERVICE, token);
1457 }
1458
1459 public final void bindApplication(String processName,
1460 ApplicationInfo appInfo, List<ProviderInfo> providers,
1461 ComponentName instrumentationName, String profileFile,
1462 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -07001463 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465
1466 if (services != null) {
1467 // Setup the service cache in the ServiceManager
1468 ServiceManager.initServiceCache(services);
1469 }
1470
1471 AppBindData data = new AppBindData();
1472 data.processName = processName;
1473 data.appInfo = appInfo;
1474 data.providers = providers;
1475 data.instrumentationName = instrumentationName;
1476 data.profileFile = profileFile;
1477 data.instrumentationArgs = instrumentationArgs;
1478 data.instrumentationWatcher = instrumentationWatcher;
1479 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001480 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 data.config = config;
1482 queueOrSendMessage(H.BIND_APPLICATION, data);
1483 }
1484
1485 public final void scheduleExit() {
1486 queueOrSendMessage(H.EXIT_APPLICATION, null);
1487 }
1488
Christopher Tate5e1ab332009-09-01 20:32:49 -07001489 public final void scheduleSuicide() {
1490 queueOrSendMessage(H.SUICIDE, null);
1491 }
1492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 public void requestThumbnail(IBinder token) {
1494 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
1495 }
1496
1497 public void scheduleConfigurationChanged(Configuration config) {
1498 synchronized (mRelaunchingActivities) {
1499 mPendingConfiguration = config;
1500 }
1501 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
1502 }
1503
1504 public void updateTimeZone() {
1505 TimeZone.setDefault(null);
1506 }
1507
1508 public void processInBackground() {
1509 mH.removeMessages(H.GC_WHEN_IDLE);
1510 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1511 }
1512
1513 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
1514 DumpServiceInfo data = new DumpServiceInfo();
1515 data.fd = fd;
1516 data.service = servicetoken;
1517 data.args = args;
1518 data.dumped = false;
1519 queueOrSendMessage(H.DUMP_SERVICE, data);
1520 synchronized (data) {
1521 while (!data.dumped) {
1522 try {
1523 data.wait();
1524 } catch (InterruptedException e) {
1525 // no need to do anything here, we will keep waiting until
1526 // dumped is set
1527 }
1528 }
1529 }
1530 }
1531
1532 // This function exists to make sure all receiver dispatching is
1533 // correctly ordered, since these are one-way calls and the binder driver
1534 // applies transaction ordering per object for such calls.
1535 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001536 int resultCode, String dataStr, Bundle extras, boolean ordered,
1537 boolean sticky) throws RemoteException {
1538 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
Bob Leee5408332009-09-04 18:31:17 -07001540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 public void scheduleLowMemory() {
1542 queueOrSendMessage(H.LOW_MEMORY, null);
1543 }
1544
1545 public void scheduleActivityConfigurationChanged(IBinder token) {
1546 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
1547 }
1548
1549 public void requestPss() {
1550 try {
1551 ActivityManagerNative.getDefault().reportPss(this,
1552 (int)Process.getPss(Process.myPid()));
1553 } catch (RemoteException e) {
1554 }
1555 }
Bob Leee5408332009-09-04 18:31:17 -07001556
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001557 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
1558 ProfilerControlData pcd = new ProfilerControlData();
1559 pcd.path = path;
1560 pcd.fd = fd;
1561 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001562 }
1563
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001564 public void setSchedulingGroup(int group) {
1565 // Note: do this immediately, since going into the foreground
1566 // should happen regardless of what pending work we have to do
1567 // and the activity manager will wait for us to report back that
1568 // we are done before sending us to the background.
1569 try {
1570 Process.setProcessGroup(Process.myPid(), group);
1571 } catch (Exception e) {
1572 Log.w(TAG, "Failed setting process group to " + group, e);
1573 }
1574 }
Bob Leee5408332009-09-04 18:31:17 -07001575
Dianne Hackborn3025ef32009-08-31 21:31:47 -07001576 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
1577 Debug.getMemoryInfo(outInfo);
1578 }
Bob Leee5408332009-09-04 18:31:17 -07001579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 @Override
1581 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1582 long nativeMax = Debug.getNativeHeapSize() / 1024;
1583 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1584 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1585
1586 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
1587 Debug.getMemoryInfo(memInfo);
1588
1589 final int nativeShared = memInfo.nativeSharedDirty;
1590 final int dalvikShared = memInfo.dalvikSharedDirty;
1591 final int otherShared = memInfo.otherSharedDirty;
1592
1593 final int nativePrivate = memInfo.nativePrivateDirty;
1594 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
1595 final int otherPrivate = memInfo.otherPrivateDirty;
1596
1597 Runtime runtime = Runtime.getRuntime();
1598
1599 long dalvikMax = runtime.totalMemory() / 1024;
1600 long dalvikFree = runtime.freeMemory() / 1024;
1601 long dalvikAllocated = dalvikMax - dalvikFree;
1602 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1603 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
1604 long appContextInstanceCount = ApplicationContext.getInstanceCount();
1605 long activityInstanceCount = Activity.getInstanceCount();
1606 int globalAssetCount = AssetManager.getGlobalAssetCount();
1607 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1608 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1609 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1610 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1611 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
1612 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
1613 SQLiteDebug.PagerStats stats = new SQLiteDebug.PagerStats();
1614 SQLiteDebug.getPagerStats(stats);
Bob Leee5408332009-09-04 18:31:17 -07001615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 // Check to see if we were called by checkin server. If so, print terse format.
1617 boolean doCheckinFormat = false;
1618 if (args != null) {
1619 for (String arg : args) {
1620 if ("-c".equals(arg)) doCheckinFormat = true;
1621 }
1622 }
Bob Leee5408332009-09-04 18:31:17 -07001623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 // For checkin, we print one long comma-separated list of values
1625 if (doCheckinFormat) {
1626 // NOTE: if you change anything significant below, also consider changing
1627 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -07001628 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -07001630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 // Header
1632 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
1633 pw.print(Process.myPid()); pw.print(',');
1634 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 // Heap info - max
1637 pw.print(nativeMax); pw.print(',');
1638 pw.print(dalvikMax); pw.print(',');
1639 pw.print("N/A,");
1640 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 // Heap info - allocated
1643 pw.print(nativeAllocated); pw.print(',');
1644 pw.print(dalvikAllocated); pw.print(',');
1645 pw.print("N/A,");
1646 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 // Heap info - free
1649 pw.print(nativeFree); pw.print(',');
1650 pw.print(dalvikFree); pw.print(',');
1651 pw.print("N/A,");
1652 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 // Heap info - proportional set size
1655 pw.print(memInfo.nativePss); pw.print(',');
1656 pw.print(memInfo.dalvikPss); pw.print(',');
1657 pw.print(memInfo.otherPss); pw.print(',');
1658 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -07001661 pw.print(nativeShared); pw.print(',');
1662 pw.print(dalvikShared); pw.print(',');
1663 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -07001667 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 pw.print(dalvikPrivate); pw.print(',');
1669 pw.print(otherPrivate); pw.print(',');
1670 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 // Object counts
1673 pw.print(viewInstanceCount); pw.print(',');
1674 pw.print(viewRootInstanceCount); pw.print(',');
1675 pw.print(appContextInstanceCount); pw.print(',');
1676 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 pw.print(globalAssetCount); pw.print(',');
1679 pw.print(globalAssetManagerCount); pw.print(',');
1680 pw.print(binderLocalObjectCount); pw.print(',');
1681 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 pw.print(binderDeathObjectCount); pw.print(',');
1684 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 // SQL
1687 pw.print(sqliteAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001688 pw.print(stats.databaseBytes / 1024); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 pw.print(stats.numPagers); pw.print(',');
1690 pw.print((stats.totalBytes - stats.referencedBytes) / 1024); pw.print(',');
1691 pw.print(stats.referencedBytes / 1024); pw.print('\n');
Bob Leee5408332009-09-04 18:31:17 -07001692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 return;
1694 }
Bob Leee5408332009-09-04 18:31:17 -07001695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 // otherwise, show human-readable format
1697 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
1698 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
1699 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
1700 nativeAllocated + dalvikAllocated);
1701 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
1702 nativeFree + dalvikFree);
1703
1704 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
1705 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
1706
1707 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
1708 nativeShared + dalvikShared + otherShared);
1709 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
1710 nativePrivate + dalvikPrivate + otherPrivate);
1711
1712 pw.println(" ");
1713 pw.println(" Objects");
1714 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
1715 viewRootInstanceCount);
1716
1717 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1718 "Activities:", activityInstanceCount);
1719
1720 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1721 "AssetManagers:", globalAssetManagerCount);
1722
1723 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1724 "Proxy Binders:", binderProxyObjectCount);
1725 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1726
1727 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 // SQLite mem info
1730 pw.println(" ");
1731 pw.println(" SQL");
1732 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "dbFiles:",
1733 stats.databaseBytes / 1024);
1734 printRow(pw, TWO_COUNT_COLUMNS, "numPagers:", stats.numPagers, "inactivePageKB:",
1735 (stats.totalBytes - stats.referencedBytes) / 1024);
1736 printRow(pw, ONE_COUNT_COLUMN, "activePageKB:", stats.referencedBytes / 1024);
Bob Leee5408332009-09-04 18:31:17 -07001737
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001738 // Asset details.
1739 String assetAlloc = AssetManager.getAssetAllocations();
1740 if (assetAlloc != null) {
1741 pw.println(" ");
1742 pw.println(" Asset Allocations");
1743 pw.print(assetAlloc);
1744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 }
1746
1747 private void printRow(PrintWriter pw, String format, Object...objs) {
1748 pw.println(String.format(format, objs));
1749 }
1750 }
1751
1752 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -07001753 private H() {
1754 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
1755 }
1756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 public static final int LAUNCH_ACTIVITY = 100;
1758 public static final int PAUSE_ACTIVITY = 101;
1759 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1760 public static final int STOP_ACTIVITY_SHOW = 103;
1761 public static final int STOP_ACTIVITY_HIDE = 104;
1762 public static final int SHOW_WINDOW = 105;
1763 public static final int HIDE_WINDOW = 106;
1764 public static final int RESUME_ACTIVITY = 107;
1765 public static final int SEND_RESULT = 108;
1766 public static final int DESTROY_ACTIVITY = 109;
1767 public static final int BIND_APPLICATION = 110;
1768 public static final int EXIT_APPLICATION = 111;
1769 public static final int NEW_INTENT = 112;
1770 public static final int RECEIVER = 113;
1771 public static final int CREATE_SERVICE = 114;
1772 public static final int SERVICE_ARGS = 115;
1773 public static final int STOP_SERVICE = 116;
1774 public static final int REQUEST_THUMBNAIL = 117;
1775 public static final int CONFIGURATION_CHANGED = 118;
1776 public static final int CLEAN_UP_CONTEXT = 119;
1777 public static final int GC_WHEN_IDLE = 120;
1778 public static final int BIND_SERVICE = 121;
1779 public static final int UNBIND_SERVICE = 122;
1780 public static final int DUMP_SERVICE = 123;
1781 public static final int LOW_MEMORY = 124;
1782 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1783 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001784 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001785 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001786 public static final int DESTROY_BACKUP_AGENT = 129;
1787 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001788 public static final int REMOVE_PROVIDER = 131;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 String codeToString(int code) {
1790 if (localLOGV) {
1791 switch (code) {
1792 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1793 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1794 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1795 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1796 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1797 case SHOW_WINDOW: return "SHOW_WINDOW";
1798 case HIDE_WINDOW: return "HIDE_WINDOW";
1799 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1800 case SEND_RESULT: return "SEND_RESULT";
1801 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1802 case BIND_APPLICATION: return "BIND_APPLICATION";
1803 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1804 case NEW_INTENT: return "NEW_INTENT";
1805 case RECEIVER: return "RECEIVER";
1806 case CREATE_SERVICE: return "CREATE_SERVICE";
1807 case SERVICE_ARGS: return "SERVICE_ARGS";
1808 case STOP_SERVICE: return "STOP_SERVICE";
1809 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1810 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1811 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1812 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1813 case BIND_SERVICE: return "BIND_SERVICE";
1814 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1815 case DUMP_SERVICE: return "DUMP_SERVICE";
1816 case LOW_MEMORY: return "LOW_MEMORY";
1817 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1818 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001819 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001820 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1821 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001822 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001823 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825 }
1826 return "(unknown)";
1827 }
1828 public void handleMessage(Message msg) {
1829 switch (msg.what) {
1830 case LAUNCH_ACTIVITY: {
1831 ActivityRecord r = (ActivityRecord)msg.obj;
1832
1833 r.packageInfo = getPackageInfoNoCheck(
1834 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001835 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 } break;
1837 case RELAUNCH_ACTIVITY: {
1838 ActivityRecord r = (ActivityRecord)msg.obj;
1839 handleRelaunchActivity(r, msg.arg1);
1840 } break;
1841 case PAUSE_ACTIVITY:
1842 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001843 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 break;
1845 case PAUSE_ACTIVITY_FINISHING:
1846 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1847 break;
1848 case STOP_ACTIVITY_SHOW:
1849 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1850 break;
1851 case STOP_ACTIVITY_HIDE:
1852 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1853 break;
1854 case SHOW_WINDOW:
1855 handleWindowVisibility((IBinder)msg.obj, true);
1856 break;
1857 case HIDE_WINDOW:
1858 handleWindowVisibility((IBinder)msg.obj, false);
1859 break;
1860 case RESUME_ACTIVITY:
1861 handleResumeActivity((IBinder)msg.obj, true,
1862 msg.arg1 != 0);
1863 break;
1864 case SEND_RESULT:
1865 handleSendResult((ResultData)msg.obj);
1866 break;
1867 case DESTROY_ACTIVITY:
1868 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1869 msg.arg2, false);
1870 break;
1871 case BIND_APPLICATION:
1872 AppBindData data = (AppBindData)msg.obj;
1873 handleBindApplication(data);
1874 break;
1875 case EXIT_APPLICATION:
1876 if (mInitialApplication != null) {
1877 mInitialApplication.onTerminate();
1878 }
1879 Looper.myLooper().quit();
1880 break;
1881 case NEW_INTENT:
1882 handleNewIntent((NewIntentData)msg.obj);
1883 break;
1884 case RECEIVER:
1885 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001886 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 break;
1888 case CREATE_SERVICE:
1889 handleCreateService((CreateServiceData)msg.obj);
1890 break;
1891 case BIND_SERVICE:
1892 handleBindService((BindServiceData)msg.obj);
1893 break;
1894 case UNBIND_SERVICE:
1895 handleUnbindService((BindServiceData)msg.obj);
1896 break;
1897 case SERVICE_ARGS:
1898 handleServiceArgs((ServiceArgsData)msg.obj);
1899 break;
1900 case STOP_SERVICE:
1901 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001902 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 break;
1904 case REQUEST_THUMBNAIL:
1905 handleRequestThumbnail((IBinder)msg.obj);
1906 break;
1907 case CONFIGURATION_CHANGED:
1908 handleConfigurationChanged((Configuration)msg.obj);
1909 break;
1910 case CLEAN_UP_CONTEXT:
1911 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1912 cci.context.performFinalCleanup(cci.who, cci.what);
1913 break;
1914 case GC_WHEN_IDLE:
1915 scheduleGcIdler();
1916 break;
1917 case DUMP_SERVICE:
1918 handleDumpService((DumpServiceInfo)msg.obj);
1919 break;
1920 case LOW_MEMORY:
1921 handleLowMemory();
1922 break;
1923 case ACTIVITY_CONFIGURATION_CHANGED:
1924 handleActivityConfigurationChanged((IBinder)msg.obj);
1925 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001926 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001927 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001928 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001929 case CREATE_BACKUP_AGENT:
1930 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1931 break;
1932 case DESTROY_BACKUP_AGENT:
1933 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1934 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001935 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001936 Process.killProcess(Process.myPid());
1937 break;
1938 case REMOVE_PROVIDER:
1939 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001940 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 }
1942 }
Bob Leee5408332009-09-04 18:31:17 -07001943
1944 void maybeSnapshot() {
1945 if (mBoundApplication != null) {
1946 SamplingProfilerIntegration.writeSnapshot(
1947 mBoundApplication.processName);
1948 }
1949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 }
1951
1952 private final class Idler implements MessageQueue.IdleHandler {
1953 public final boolean queueIdle() {
1954 ActivityRecord a = mNewActivities;
1955 if (a != null) {
1956 mNewActivities = null;
1957 IActivityManager am = ActivityManagerNative.getDefault();
1958 ActivityRecord prev;
1959 do {
1960 if (localLOGV) Log.v(
1961 TAG, "Reporting idle of " + a +
1962 " finished=" +
1963 (a.activity != null ? a.activity.mFinished : false));
1964 if (a.activity != null && !a.activity.mFinished) {
1965 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001966 am.activityIdle(a.token, a.createdConfig);
1967 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 } catch (RemoteException ex) {
1969 }
1970 }
1971 prev = a;
1972 a = a.nextIdle;
1973 prev.nextIdle = null;
1974 } while (a != null);
1975 }
1976 return false;
1977 }
1978 }
1979
1980 final class GcIdler implements MessageQueue.IdleHandler {
1981 public final boolean queueIdle() {
1982 doGcIfNeeded();
1983 return false;
1984 }
1985 }
1986
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001987 private final static class ResourcesKey {
1988 final private String mResDir;
1989 final private float mScale;
1990 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001991
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001992 ResourcesKey(String resDir, float scale) {
1993 mResDir = resDir;
1994 mScale = scale;
1995 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1996 }
Bob Leee5408332009-09-04 18:31:17 -07001997
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001998 @Override
1999 public int hashCode() {
2000 return mHash;
2001 }
2002
2003 @Override
2004 public boolean equals(Object obj) {
2005 if (!(obj instanceof ResourcesKey)) {
2006 return false;
2007 }
2008 ResourcesKey peer = (ResourcesKey) obj;
2009 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
2010 }
2011 }
2012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 static IPackageManager sPackageManager;
2014
2015 final ApplicationThread mAppThread = new ApplicationThread();
2016 final Looper mLooper = Looper.myLooper();
2017 final H mH = new H();
2018 final HashMap<IBinder, ActivityRecord> mActivities
2019 = new HashMap<IBinder, ActivityRecord>();
2020 // List of new activities (via ActivityRecord.nextIdle) that should
2021 // be reported when next we idle.
2022 ActivityRecord mNewActivities = null;
2023 // Number of activities that are currently visible on-screen.
2024 int mNumVisibleActivities = 0;
2025 final HashMap<IBinder, Service> mServices
2026 = new HashMap<IBinder, Service>();
2027 AppBindData mBoundApplication;
2028 Configuration mConfiguration;
2029 Application mInitialApplication;
2030 final ArrayList<Application> mAllApplications
2031 = new ArrayList<Application>();
Christopher Tate181fafa2009-05-14 11:12:14 -07002032 // set of instantiated backup agents, keyed by package name
2033 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 static final ThreadLocal sThreadLocal = new ThreadLocal();
2035 Instrumentation mInstrumentation;
2036 String mInstrumentationAppDir = null;
2037 String mInstrumentationAppPackage = null;
2038 String mInstrumentedAppDir = null;
2039 boolean mSystemThread = false;
2040
2041 /**
2042 * Activities that are enqueued to be relaunched. This list is accessed
2043 * by multiple threads, so you must synchronize on it when accessing it.
2044 */
2045 final ArrayList<ActivityRecord> mRelaunchingActivities
2046 = new ArrayList<ActivityRecord>();
2047 Configuration mPendingConfiguration = null;
Bob Leee5408332009-09-04 18:31:17 -07002048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 // These can be accessed by multiple threads; mPackages is the lock.
2050 // XXX For now we keep around information about all packages we have
2051 // seen, not removing entries from this map.
2052 final HashMap<String, WeakReference<PackageInfo>> mPackages
2053 = new HashMap<String, WeakReference<PackageInfo>>();
2054 final HashMap<String, WeakReference<PackageInfo>> mResourcePackages
2055 = new HashMap<String, WeakReference<PackageInfo>>();
2056 Display mDisplay = null;
2057 DisplayMetrics mDisplayMetrics = null;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002058 HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
2059 = new HashMap<ResourcesKey, WeakReference<Resources> >();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060
2061 // The lock of mProviderMap protects the following variables.
2062 final HashMap<String, ProviderRecord> mProviderMap
2063 = new HashMap<String, ProviderRecord>();
2064 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
2065 = new HashMap<IBinder, ProviderRefCount>();
2066 final HashMap<IBinder, ProviderRecord> mLocalProviders
2067 = new HashMap<IBinder, ProviderRecord>();
2068
2069 final GcIdler mGcIdler = new GcIdler();
2070 boolean mGcIdlerScheduled = false;
2071
2072 public final PackageInfo getPackageInfo(String packageName, int flags) {
2073 synchronized (mPackages) {
2074 WeakReference<PackageInfo> ref;
2075 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
2076 ref = mPackages.get(packageName);
2077 } else {
2078 ref = mResourcePackages.get(packageName);
2079 }
2080 PackageInfo packageInfo = ref != null ? ref.get() : null;
2081 //Log.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
2082 if (packageInfo != null && (packageInfo.mResources == null
2083 || packageInfo.mResources.getAssets().isUpToDate())) {
2084 if (packageInfo.isSecurityViolation()
2085 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2086 throw new SecurityException(
2087 "Requesting code from " + packageName
2088 + " to be run in process "
2089 + mBoundApplication.processName
2090 + "/" + mBoundApplication.appInfo.uid);
2091 }
2092 return packageInfo;
2093 }
2094 }
2095
2096 ApplicationInfo ai = null;
2097 try {
2098 ai = getPackageManager().getApplicationInfo(packageName,
2099 PackageManager.GET_SHARED_LIBRARY_FILES);
2100 } catch (RemoteException e) {
2101 }
2102
2103 if (ai != null) {
2104 return getPackageInfo(ai, flags);
2105 }
2106
2107 return null;
2108 }
2109
2110 public final PackageInfo getPackageInfo(ApplicationInfo ai, int flags) {
2111 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2112 boolean securityViolation = includeCode && ai.uid != 0
2113 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
2114 ? ai.uid != mBoundApplication.appInfo.uid : true);
2115 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2116 |Context.CONTEXT_IGNORE_SECURITY))
2117 == Context.CONTEXT_INCLUDE_CODE) {
2118 if (securityViolation) {
2119 String msg = "Requesting code from " + ai.packageName
2120 + " (with uid " + ai.uid + ")";
2121 if (mBoundApplication != null) {
2122 msg = msg + " to be run in process "
2123 + mBoundApplication.processName + " (with uid "
2124 + mBoundApplication.appInfo.uid + ")";
2125 }
2126 throw new SecurityException(msg);
2127 }
2128 }
2129 return getPackageInfo(ai, null, securityViolation, includeCode);
2130 }
2131
2132 public final PackageInfo getPackageInfoNoCheck(ApplicationInfo ai) {
2133 return getPackageInfo(ai, null, false, true);
2134 }
2135
2136 private final PackageInfo getPackageInfo(ApplicationInfo aInfo,
2137 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
2138 synchronized (mPackages) {
2139 WeakReference<PackageInfo> ref;
2140 if (includeCode) {
2141 ref = mPackages.get(aInfo.packageName);
2142 } else {
2143 ref = mResourcePackages.get(aInfo.packageName);
2144 }
2145 PackageInfo packageInfo = ref != null ? ref.get() : null;
2146 if (packageInfo == null || (packageInfo.mResources != null
2147 && !packageInfo.mResources.getAssets().isUpToDate())) {
2148 if (localLOGV) Log.v(TAG, (includeCode ? "Loading code package "
2149 : "Loading resource-only package ") + aInfo.packageName
2150 + " (in " + (mBoundApplication != null
2151 ? mBoundApplication.processName : null)
2152 + ")");
2153 packageInfo =
2154 new PackageInfo(this, aInfo, this, baseLoader,
2155 securityViolation, includeCode &&
2156 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
2157 if (includeCode) {
2158 mPackages.put(aInfo.packageName,
2159 new WeakReference<PackageInfo>(packageInfo));
2160 } else {
2161 mResourcePackages.put(aInfo.packageName,
2162 new WeakReference<PackageInfo>(packageInfo));
2163 }
2164 }
2165 return packageInfo;
2166 }
2167 }
2168
2169 public final boolean hasPackageInfo(String packageName) {
2170 synchronized (mPackages) {
2171 WeakReference<PackageInfo> ref;
2172 ref = mPackages.get(packageName);
2173 if (ref != null && ref.get() != null) {
2174 return true;
2175 }
2176 ref = mResourcePackages.get(packageName);
2177 if (ref != null && ref.get() != null) {
2178 return true;
2179 }
2180 return false;
2181 }
2182 }
Bob Leee5408332009-09-04 18:31:17 -07002183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 ActivityThread() {
2185 }
2186
2187 public ApplicationThread getApplicationThread()
2188 {
2189 return mAppThread;
2190 }
2191
2192 public Instrumentation getInstrumentation()
2193 {
2194 return mInstrumentation;
2195 }
2196
2197 public Configuration getConfiguration() {
2198 return mConfiguration;
2199 }
2200
2201 public boolean isProfiling() {
2202 return mBoundApplication != null && mBoundApplication.profileFile != null;
2203 }
2204
2205 public String getProfileFilePath() {
2206 return mBoundApplication.profileFile;
2207 }
2208
2209 public Looper getLooper() {
2210 return mLooper;
2211 }
2212
2213 public Application getApplication() {
2214 return mInitialApplication;
2215 }
Bob Leee5408332009-09-04 18:31:17 -07002216
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002217 public String getProcessName() {
2218 return mBoundApplication.processName;
2219 }
Bob Leee5408332009-09-04 18:31:17 -07002220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 public ApplicationContext getSystemContext() {
2222 synchronized (this) {
2223 if (mSystemContext == null) {
2224 ApplicationContext context =
2225 ApplicationContext.createSystemContext(this);
Mike Cleron432b7132009-09-24 15:28:29 -07002226 PackageInfo info = new PackageInfo(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 context.init(info, null, this);
2228 context.getResources().updateConfiguration(
2229 getConfiguration(), getDisplayMetricsLocked(false));
2230 mSystemContext = context;
2231 //Log.i(TAG, "Created system resources " + context.getResources()
2232 // + ": " + context.getResources().getConfiguration());
2233 }
2234 }
2235 return mSystemContext;
2236 }
2237
Mike Cleron432b7132009-09-24 15:28:29 -07002238 public void installSystemApplicationInfo(ApplicationInfo info) {
2239 synchronized (this) {
2240 ApplicationContext context = getSystemContext();
2241 context.init(new PackageInfo(this, "android", context, info), null, this);
2242 }
2243 }
2244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 void scheduleGcIdler() {
2246 if (!mGcIdlerScheduled) {
2247 mGcIdlerScheduled = true;
2248 Looper.myQueue().addIdleHandler(mGcIdler);
2249 }
2250 mH.removeMessages(H.GC_WHEN_IDLE);
2251 }
2252
2253 void unscheduleGcIdler() {
2254 if (mGcIdlerScheduled) {
2255 mGcIdlerScheduled = false;
2256 Looper.myQueue().removeIdleHandler(mGcIdler);
2257 }
2258 mH.removeMessages(H.GC_WHEN_IDLE);
2259 }
2260
2261 void doGcIfNeeded() {
2262 mGcIdlerScheduled = false;
2263 final long now = SystemClock.uptimeMillis();
2264 //Log.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
2265 // + "m now=" + now);
2266 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
2267 //Log.i(TAG, "**** WE DO, WE DO WANT TO GC!");
2268 BinderInternal.forceGc("bg");
2269 }
2270 }
2271
2272 public final ActivityInfo resolveActivityInfo(Intent intent) {
2273 ActivityInfo aInfo = intent.resolveActivityInfo(
2274 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2275 if (aInfo == null) {
2276 // Throw an exception.
2277 Instrumentation.checkStartActivityResult(
2278 IActivityManager.START_CLASS_NOT_FOUND, intent);
2279 }
2280 return aInfo;
2281 }
Bob Leee5408332009-09-04 18:31:17 -07002282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
2285 Object lastNonConfigurationInstance) {
2286 ActivityRecord r = new ActivityRecord();
2287 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002288 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 r.intent = intent;
2290 r.state = state;
2291 r.parent = parent;
2292 r.embeddedID = id;
2293 r.activityInfo = activityInfo;
2294 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
2295 if (localLOGV) {
2296 ComponentName compname = intent.getComponent();
2297 String name;
2298 if (compname != null) {
2299 name = compname.toShortString();
2300 } else {
2301 name = "(Intent " + intent + ").getComponent() returned null";
2302 }
2303 Log.v(TAG, "Performing launch: action=" + intent.getAction()
2304 + ", comp=" + name
2305 + ", token=" + token);
2306 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07002307 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
2309
2310 public final Activity getActivity(IBinder token) {
2311 return mActivities.get(token).activity;
2312 }
2313
2314 public final void sendActivityResult(
2315 IBinder token, String id, int requestCode,
2316 int resultCode, Intent data) {
Chris Tate8a7dc172009-03-24 20:11:42 -07002317 if (DEBUG_RESULTS) Log.v(TAG, "sendActivityResult: id=" + id
2318 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2320 list.add(new ResultInfo(id, requestCode, resultCode, data));
2321 mAppThread.scheduleSendResult(token, list);
2322 }
2323
2324 // if the thread hasn't started yet, we don't have the handler, so just
2325 // save the messages until we're ready.
2326 private final void queueOrSendMessage(int what, Object obj) {
2327 queueOrSendMessage(what, obj, 0, 0);
2328 }
2329
2330 private final void queueOrSendMessage(int what, Object obj, int arg1) {
2331 queueOrSendMessage(what, obj, arg1, 0);
2332 }
2333
2334 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
2335 synchronized (this) {
2336 if (localLOGV) Log.v(
2337 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2338 + ": " + arg1 + " / " + obj);
2339 Message msg = Message.obtain();
2340 msg.what = what;
2341 msg.obj = obj;
2342 msg.arg1 = arg1;
2343 msg.arg2 = arg2;
2344 mH.sendMessage(msg);
2345 }
2346 }
2347
2348 final void scheduleContextCleanup(ApplicationContext context, String who,
2349 String what) {
2350 ContextCleanupInfo cci = new ContextCleanupInfo();
2351 cci.context = context;
2352 cci.who = who;
2353 cci.what = what;
2354 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
2355 }
2356
Christopher Tateb70f3df2009-04-07 16:07:59 -07002357 private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
2359
2360 ActivityInfo aInfo = r.activityInfo;
2361 if (r.packageInfo == null) {
2362 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
2363 Context.CONTEXT_INCLUDE_CODE);
2364 }
Bob Leee5408332009-09-04 18:31:17 -07002365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 ComponentName component = r.intent.getComponent();
2367 if (component == null) {
2368 component = r.intent.resolveActivity(
2369 mInitialApplication.getPackageManager());
2370 r.intent.setComponent(component);
2371 }
2372
2373 if (r.activityInfo.targetActivity != null) {
2374 component = new ComponentName(r.activityInfo.packageName,
2375 r.activityInfo.targetActivity);
2376 }
2377
2378 Activity activity = null;
2379 try {
2380 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
2381 activity = mInstrumentation.newActivity(
2382 cl, component.getClassName(), r.intent);
2383 r.intent.setExtrasClassLoader(cl);
2384 if (r.state != null) {
2385 r.state.setClassLoader(cl);
2386 }
2387 } catch (Exception e) {
2388 if (!mInstrumentation.onException(activity, e)) {
2389 throw new RuntimeException(
2390 "Unable to instantiate activity " + component
2391 + ": " + e.toString(), e);
2392 }
2393 }
2394
2395 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002396 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 if (localLOGV) Log.v(TAG, "Performing launch of " + r);
2399 if (localLOGV) Log.v(
2400 TAG, r + ": app=" + app
2401 + ", appName=" + app.getPackageName()
2402 + ", pkg=" + r.packageInfo.getPackageName()
2403 + ", comp=" + r.intent.getComponent().toShortString()
2404 + ", dir=" + r.packageInfo.getAppDir());
2405
2406 if (activity != null) {
2407 ApplicationContext appContext = new ApplicationContext();
2408 appContext.init(r.packageInfo, r.token, this);
2409 appContext.setOuterContext(activity);
2410 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
2411 Configuration config = new Configuration(mConfiguration);
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002412 if (DEBUG_CONFIGURATION) Log.v(TAG, "Launching activity "
2413 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002414 activity.attach(appContext, this, getInstrumentation(), r.token,
2415 r.ident, app, r.intent, r.activityInfo, title, r.parent,
2416 r.embeddedID, r.lastNonConfigurationInstance,
2417 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07002418
Christopher Tateb70f3df2009-04-07 16:07:59 -07002419 if (customIntent != null) {
2420 activity.mIntent = customIntent;
2421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 r.lastNonConfigurationInstance = null;
2423 r.lastNonConfigurationChildInstances = null;
2424 activity.mStartedActivity = false;
2425 int theme = r.activityInfo.getThemeResource();
2426 if (theme != 0) {
2427 activity.setTheme(theme);
2428 }
2429
2430 activity.mCalled = false;
2431 mInstrumentation.callActivityOnCreate(activity, r.state);
2432 if (!activity.mCalled) {
2433 throw new SuperNotCalledException(
2434 "Activity " + r.intent.getComponent().toShortString() +
2435 " did not call through to super.onCreate()");
2436 }
2437 r.activity = activity;
2438 r.stopped = true;
2439 if (!r.activity.mFinished) {
2440 activity.performStart();
2441 r.stopped = false;
2442 }
2443 if (!r.activity.mFinished) {
2444 if (r.state != null) {
2445 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2446 }
2447 }
2448 if (!r.activity.mFinished) {
2449 activity.mCalled = false;
2450 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2451 if (!activity.mCalled) {
2452 throw new SuperNotCalledException(
2453 "Activity " + r.intent.getComponent().toShortString() +
2454 " did not call through to super.onPostCreate()");
2455 }
2456 }
2457 r.state = null;
2458 }
2459 r.paused = true;
2460
2461 mActivities.put(r.token, r);
2462
2463 } catch (SuperNotCalledException e) {
2464 throw e;
2465
2466 } catch (Exception e) {
2467 if (!mInstrumentation.onException(activity, e)) {
2468 throw new RuntimeException(
2469 "Unable to start activity " + component
2470 + ": " + e.toString(), e);
2471 }
2472 }
2473
2474 return activity;
2475 }
2476
Christopher Tateb70f3df2009-04-07 16:07:59 -07002477 private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 // If we are getting ready to gc after going to the background, well
2479 // we are back active so skip it.
2480 unscheduleGcIdler();
2481
2482 if (localLOGV) Log.v(
2483 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002484 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485
2486 if (a != null) {
Dianne Hackborne88846e2009-09-30 21:34:25 -07002487 r.createdConfig = new Configuration(a.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 handleResumeActivity(r.token, false, r.isForward);
2489
2490 if (!r.activity.mFinished && r.startsNotResumed) {
2491 // The activity manager actually wants this one to start out
2492 // paused, because it needs to be visible but isn't in the
2493 // foreground. We accomplish this by going through the
2494 // normal startup (because activities expect to go through
2495 // onResume() the first time they run, before their window
2496 // is displayed), and then pausing it. However, in this case
2497 // we do -not- need to do the full pause cycle (of freezing
2498 // and such) because the activity manager assumes it can just
2499 // retain the current state it has.
2500 try {
2501 r.activity.mCalled = false;
2502 mInstrumentation.callActivityOnPause(r.activity);
2503 if (!r.activity.mCalled) {
2504 throw new SuperNotCalledException(
2505 "Activity " + r.intent.getComponent().toShortString() +
2506 " did not call through to super.onPause()");
2507 }
2508
2509 } catch (SuperNotCalledException e) {
2510 throw e;
2511
2512 } catch (Exception e) {
2513 if (!mInstrumentation.onException(r.activity, e)) {
2514 throw new RuntimeException(
2515 "Unable to pause activity "
2516 + r.intent.getComponent().toShortString()
2517 + ": " + e.toString(), e);
2518 }
2519 }
2520 r.paused = true;
2521 }
2522 } else {
2523 // If there was an error, for any reason, tell the activity
2524 // manager to stop us.
2525 try {
2526 ActivityManagerNative.getDefault()
2527 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2528 } catch (RemoteException ex) {
2529 }
2530 }
2531 }
2532
2533 private final void deliverNewIntents(ActivityRecord r,
2534 List<Intent> intents) {
2535 final int N = intents.size();
2536 for (int i=0; i<N; i++) {
2537 Intent intent = intents.get(i);
2538 intent.setExtrasClassLoader(r.activity.getClassLoader());
2539 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2540 }
2541 }
2542
2543 public final void performNewIntents(IBinder token,
2544 List<Intent> intents) {
2545 ActivityRecord r = mActivities.get(token);
2546 if (r != null) {
2547 final boolean resumed = !r.paused;
2548 if (resumed) {
2549 mInstrumentation.callActivityOnPause(r.activity);
2550 }
2551 deliverNewIntents(r, intents);
2552 if (resumed) {
2553 mInstrumentation.callActivityOnResume(r.activity);
2554 }
2555 }
2556 }
Bob Leee5408332009-09-04 18:31:17 -07002557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 private final void handleNewIntent(NewIntentData data) {
2559 performNewIntents(data.token, data.intents);
2560 }
2561
2562 private final void handleReceiver(ReceiverData data) {
2563 // If we are getting ready to gc after going to the background, well
2564 // we are back active so skip it.
2565 unscheduleGcIdler();
2566
2567 String component = data.intent.getComponent().getClassName();
2568
2569 PackageInfo packageInfo = getPackageInfoNoCheck(
2570 data.info.applicationInfo);
2571
2572 IActivityManager mgr = ActivityManagerNative.getDefault();
2573
2574 BroadcastReceiver receiver = null;
2575 try {
2576 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2577 data.intent.setExtrasClassLoader(cl);
2578 if (data.resultExtras != null) {
2579 data.resultExtras.setClassLoader(cl);
2580 }
2581 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2582 } catch (Exception e) {
2583 try {
2584 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2585 data.resultData, data.resultExtras, data.resultAbort);
2586 } catch (RemoteException ex) {
2587 }
2588 throw new RuntimeException(
2589 "Unable to instantiate receiver " + component
2590 + ": " + e.toString(), e);
2591 }
2592
2593 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002594 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 if (localLOGV) Log.v(
2597 TAG, "Performing receive of " + data.intent
2598 + ": app=" + app
2599 + ", appName=" + app.getPackageName()
2600 + ", pkg=" + packageInfo.getPackageName()
2601 + ", comp=" + data.intent.getComponent().toShortString()
2602 + ", dir=" + packageInfo.getAppDir());
2603
2604 ApplicationContext context = (ApplicationContext)app.getBaseContext();
2605 receiver.setOrderedHint(true);
2606 receiver.setResult(data.resultCode, data.resultData,
2607 data.resultExtras);
2608 receiver.setOrderedHint(data.sync);
2609 receiver.onReceive(context.getReceiverRestrictedContext(),
2610 data.intent);
2611 } catch (Exception e) {
2612 try {
2613 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2614 data.resultData, data.resultExtras, data.resultAbort);
2615 } catch (RemoteException ex) {
2616 }
2617 if (!mInstrumentation.onException(receiver, e)) {
2618 throw new RuntimeException(
2619 "Unable to start receiver " + component
2620 + ": " + e.toString(), e);
2621 }
2622 }
2623
2624 try {
2625 if (data.sync) {
2626 mgr.finishReceiver(
2627 mAppThread.asBinder(), receiver.getResultCode(),
2628 receiver.getResultData(), receiver.getResultExtras(false),
2629 receiver.getAbortBroadcast());
2630 } else {
2631 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
2632 }
2633 } catch (RemoteException ex) {
2634 }
2635 }
2636
Christopher Tate181fafa2009-05-14 11:12:14 -07002637 // Instantiate a BackupAgent and tell it that it's alive
2638 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
2639 if (DEBUG_BACKUP) Log.v(TAG, "handleCreateBackupAgent: " + data);
2640
2641 // no longer idle; we have backup work to do
2642 unscheduleGcIdler();
2643
2644 // instantiate the BackupAgent class named in the manifest
2645 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2646 String packageName = packageInfo.mPackageName;
2647 if (mBackupAgents.get(packageName) != null) {
2648 Log.d(TAG, "BackupAgent " + " for " + packageName
2649 + " already exists");
2650 return;
2651 }
Bob Leee5408332009-09-04 18:31:17 -07002652
Christopher Tate181fafa2009-05-14 11:12:14 -07002653 BackupAgent agent = null;
2654 String classname = data.appInfo.backupAgentName;
2655 if (classname == null) {
2656 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
2657 Log.e(TAG, "Attempted incremental backup but no defined agent for "
2658 + packageName);
2659 return;
2660 }
2661 classname = "android.app.FullBackupAgent";
2662 }
2663 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002664 IBinder binder = null;
2665 try {
2666 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2667 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
2668
2669 // set up the agent's context
2670 if (DEBUG_BACKUP) Log.v(TAG, "Initializing BackupAgent "
2671 + data.appInfo.backupAgentName);
2672
2673 ApplicationContext context = new ApplicationContext();
2674 context.init(packageInfo, null, this);
2675 context.setOuterContext(agent);
2676 agent.attach(context);
2677
2678 agent.onCreate();
2679 binder = agent.onBind();
2680 mBackupAgents.put(packageName, agent);
2681 } catch (Exception e) {
2682 // If this is during restore, fail silently; otherwise go
2683 // ahead and let the user see the crash.
2684 Log.e(TAG, "Agent threw during creation: " + e);
2685 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
2686 throw e;
2687 }
2688 // falling through with 'binder' still null
2689 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002690
2691 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002692 try {
2693 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2694 } catch (RemoteException e) {
2695 // nothing to do.
2696 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002697 } catch (Exception e) {
2698 throw new RuntimeException("Unable to create BackupAgent "
2699 + data.appInfo.backupAgentName + ": " + e.toString(), e);
2700 }
2701 }
2702
2703 // Tear down a BackupAgent
2704 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
2705 if (DEBUG_BACKUP) Log.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002706
Christopher Tate181fafa2009-05-14 11:12:14 -07002707 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2708 String packageName = packageInfo.mPackageName;
2709 BackupAgent agent = mBackupAgents.get(packageName);
2710 if (agent != null) {
2711 try {
2712 agent.onDestroy();
2713 } catch (Exception e) {
2714 Log.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
2715 e.printStackTrace();
2716 }
2717 mBackupAgents.remove(packageName);
2718 } else {
2719 Log.w(TAG, "Attempt to destroy unknown backup agent " + data);
2720 }
2721 }
2722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 private final void handleCreateService(CreateServiceData data) {
2724 // If we are getting ready to gc after going to the background, well
2725 // we are back active so skip it.
2726 unscheduleGcIdler();
2727
2728 PackageInfo packageInfo = getPackageInfoNoCheck(
2729 data.info.applicationInfo);
2730 Service service = null;
2731 try {
2732 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2733 service = (Service) cl.loadClass(data.info.name).newInstance();
2734 } catch (Exception e) {
2735 if (!mInstrumentation.onException(service, e)) {
2736 throw new RuntimeException(
2737 "Unable to instantiate service " + data.info.name
2738 + ": " + e.toString(), e);
2739 }
2740 }
2741
2742 try {
2743 if (localLOGV) Log.v(TAG, "Creating service " + data.info.name);
2744
2745 ApplicationContext context = new ApplicationContext();
2746 context.init(packageInfo, null, this);
2747
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002748 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 context.setOuterContext(service);
2750 service.attach(context, this, data.info.name, data.token, app,
2751 ActivityManagerNative.getDefault());
2752 service.onCreate();
2753 mServices.put(data.token, service);
2754 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002755 ActivityManagerNative.getDefault().serviceDoneExecuting(
2756 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 } catch (RemoteException e) {
2758 // nothing to do.
2759 }
2760 } catch (Exception e) {
2761 if (!mInstrumentation.onException(service, e)) {
2762 throw new RuntimeException(
2763 "Unable to create service " + data.info.name
2764 + ": " + e.toString(), e);
2765 }
2766 }
2767 }
2768
2769 private final void handleBindService(BindServiceData data) {
2770 Service s = mServices.get(data.token);
2771 if (s != null) {
2772 try {
2773 data.intent.setExtrasClassLoader(s.getClassLoader());
2774 try {
2775 if (!data.rebind) {
2776 IBinder binder = s.onBind(data.intent);
2777 ActivityManagerNative.getDefault().publishService(
2778 data.token, data.intent, binder);
2779 } else {
2780 s.onRebind(data.intent);
2781 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002782 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 }
2784 } catch (RemoteException ex) {
2785 }
2786 } catch (Exception e) {
2787 if (!mInstrumentation.onException(s, e)) {
2788 throw new RuntimeException(
2789 "Unable to bind to service " + s
2790 + " with " + data.intent + ": " + e.toString(), e);
2791 }
2792 }
2793 }
2794 }
2795
2796 private final void handleUnbindService(BindServiceData data) {
2797 Service s = mServices.get(data.token);
2798 if (s != null) {
2799 try {
2800 data.intent.setExtrasClassLoader(s.getClassLoader());
2801 boolean doRebind = s.onUnbind(data.intent);
2802 try {
2803 if (doRebind) {
2804 ActivityManagerNative.getDefault().unbindFinished(
2805 data.token, data.intent, doRebind);
2806 } else {
2807 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002808 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 }
2810 } catch (RemoteException ex) {
2811 }
2812 } catch (Exception e) {
2813 if (!mInstrumentation.onException(s, e)) {
2814 throw new RuntimeException(
2815 "Unable to unbind to service " + s
2816 + " with " + data.intent + ": " + e.toString(), e);
2817 }
2818 }
2819 }
2820 }
2821
2822 private void handleDumpService(DumpServiceInfo info) {
2823 try {
2824 Service s = mServices.get(info.service);
2825 if (s != null) {
2826 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2827 s.dump(info.fd, pw, info.args);
2828 pw.close();
2829 }
2830 } finally {
2831 synchronized (info) {
2832 info.dumped = true;
2833 info.notifyAll();
2834 }
2835 }
2836 }
2837
2838 private final void handleServiceArgs(ServiceArgsData data) {
2839 Service s = mServices.get(data.token);
2840 if (s != null) {
2841 try {
2842 if (data.args != null) {
2843 data.args.setExtrasClassLoader(s.getClassLoader());
2844 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002845 int res = s.onStartCommand(data.args, data.flags, data.startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002847 ActivityManagerNative.getDefault().serviceDoneExecuting(
2848 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 } catch (RemoteException e) {
2850 // nothing to do.
2851 }
2852 } catch (Exception e) {
2853 if (!mInstrumentation.onException(s, e)) {
2854 throw new RuntimeException(
2855 "Unable to start service " + s
2856 + " with " + data.args + ": " + e.toString(), e);
2857 }
2858 }
2859 }
2860 }
2861
2862 private final void handleStopService(IBinder token) {
2863 Service s = mServices.remove(token);
2864 if (s != null) {
2865 try {
2866 if (localLOGV) Log.v(TAG, "Destroying service " + s);
2867 s.onDestroy();
2868 Context context = s.getBaseContext();
2869 if (context instanceof ApplicationContext) {
2870 final String who = s.getClassName();
2871 ((ApplicationContext) context).scheduleFinalCleanup(who, "Service");
2872 }
2873 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002874 ActivityManagerNative.getDefault().serviceDoneExecuting(
2875 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 } catch (RemoteException e) {
2877 // nothing to do.
2878 }
2879 } catch (Exception e) {
2880 if (!mInstrumentation.onException(s, e)) {
2881 throw new RuntimeException(
2882 "Unable to stop service " + s
2883 + ": " + e.toString(), e);
2884 }
2885 }
2886 }
2887 //Log.i(TAG, "Running services: " + mServices);
2888 }
2889
2890 public final ActivityRecord performResumeActivity(IBinder token,
2891 boolean clearHide) {
2892 ActivityRecord r = mActivities.get(token);
2893 if (localLOGV) Log.v(TAG, "Performing resume of " + r
2894 + " finished=" + r.activity.mFinished);
2895 if (r != null && !r.activity.mFinished) {
2896 if (clearHide) {
2897 r.hideForNow = false;
2898 r.activity.mStartedActivity = false;
2899 }
2900 try {
2901 if (r.pendingIntents != null) {
2902 deliverNewIntents(r, r.pendingIntents);
2903 r.pendingIntents = null;
2904 }
2905 if (r.pendingResults != null) {
2906 deliverResults(r, r.pendingResults);
2907 r.pendingResults = null;
2908 }
2909 r.activity.performResume();
2910
Bob Leee5408332009-09-04 18:31:17 -07002911 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 r.paused = false;
2915 r.stopped = false;
2916 if (r.activity.mStartedActivity) {
2917 r.hideForNow = true;
2918 }
2919 r.state = null;
2920 } catch (Exception e) {
2921 if (!mInstrumentation.onException(r.activity, e)) {
2922 throw new RuntimeException(
2923 "Unable to resume activity "
2924 + r.intent.getComponent().toShortString()
2925 + ": " + e.toString(), e);
2926 }
2927 }
2928 }
2929 return r;
2930 }
2931
2932 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2933 // If we are getting ready to gc after going to the background, well
2934 // we are back active so skip it.
2935 unscheduleGcIdler();
2936
2937 ActivityRecord r = performResumeActivity(token, clearHide);
2938
2939 if (r != null) {
2940 final Activity a = r.activity;
2941
2942 if (localLOGV) Log.v(
2943 TAG, "Resume " + r + " started activity: " +
2944 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2945 + ", finished: " + a.mFinished);
2946
2947 final int forwardBit = isForward ?
2948 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 // If the window hasn't yet been added to the window manager,
2951 // and this guy didn't finish itself or start another activity,
2952 // then go ahead and add the window.
2953 if (r.window == null && !a.mFinished && !a.mStartedActivity) {
2954 r.window = r.activity.getWindow();
2955 View decor = r.window.getDecorView();
2956 decor.setVisibility(View.INVISIBLE);
2957 ViewManager wm = a.getWindowManager();
2958 WindowManager.LayoutParams l = r.window.getAttributes();
2959 a.mDecor = decor;
2960 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2961 l.softInputMode |= forwardBit;
2962 if (a.mVisibleFromClient) {
2963 a.mWindowAdded = true;
2964 wm.addView(decor, l);
2965 }
2966
2967 // If the window has already been added, but during resume
2968 // we started another activity, then don't yet make the
2969 // window visisble.
2970 } else if (a.mStartedActivity) {
2971 if (localLOGV) Log.v(
2972 TAG, "Launch " + r + " mStartedActivity set");
2973 r.hideForNow = true;
2974 }
2975
2976 // The window is now visible if it has been added, we are not
2977 // simply finishing, and we are not starting another activity.
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002978 if (!r.activity.mFinished && !a.mStartedActivity
2979 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 if (r.newConfig != null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002981 if (DEBUG_CONFIGURATION) Log.v(TAG, "Resuming activity "
2982 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 performConfigurationChanged(r.activity, r.newConfig);
2984 r.newConfig = null;
2985 }
2986 if (localLOGV) Log.v(TAG, "Resuming " + r + " with isForward="
2987 + isForward);
2988 WindowManager.LayoutParams l = r.window.getAttributes();
2989 if ((l.softInputMode
2990 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2991 != forwardBit) {
2992 l.softInputMode = (l.softInputMode
2993 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2994 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002995 if (r.activity.mVisibleFromClient) {
2996 ViewManager wm = a.getWindowManager();
2997 View decor = r.window.getDecorView();
2998 wm.updateViewLayout(decor, l);
2999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 }
3001 r.activity.mVisibleFromServer = true;
3002 mNumVisibleActivities++;
3003 if (r.activity.mVisibleFromClient) {
3004 r.activity.makeVisible();
3005 }
3006 }
3007
3008 r.nextIdle = mNewActivities;
3009 mNewActivities = r;
3010 if (localLOGV) Log.v(
3011 TAG, "Scheduling idle handler for " + r);
3012 Looper.myQueue().addIdleHandler(new Idler());
3013
3014 } else {
3015 // If an exception was thrown when trying to resume, then
3016 // just end this activity.
3017 try {
3018 ActivityManagerNative.getDefault()
3019 .finishActivity(token, Activity.RESULT_CANCELED, null);
3020 } catch (RemoteException ex) {
3021 }
3022 }
3023 }
3024
3025 private int mThumbnailWidth = -1;
3026 private int mThumbnailHeight = -1;
3027
3028 private final Bitmap createThumbnailBitmap(ActivityRecord r) {
3029 Bitmap thumbnail = null;
3030 try {
3031 int w = mThumbnailWidth;
3032 int h;
3033 if (w < 0) {
3034 Resources res = r.activity.getResources();
3035 mThumbnailHeight = h =
3036 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
3037
3038 mThumbnailWidth = w =
3039 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
3040 } else {
3041 h = mThumbnailHeight;
3042 }
3043
3044 // XXX Only set hasAlpha if needed?
3045 thumbnail = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
3046 thumbnail.eraseColor(0);
3047 Canvas cv = new Canvas(thumbnail);
3048 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
3049 thumbnail = null;
3050 }
3051 } catch (Exception e) {
3052 if (!mInstrumentation.onException(r.activity, e)) {
3053 throw new RuntimeException(
3054 "Unable to create thumbnail of "
3055 + r.intent.getComponent().toShortString()
3056 + ": " + e.toString(), e);
3057 }
3058 thumbnail = null;
3059 }
3060
3061 return thumbnail;
3062 }
3063
3064 private final void handlePauseActivity(IBinder token, boolean finished,
3065 boolean userLeaving, int configChanges) {
3066 ActivityRecord r = mActivities.get(token);
3067 if (r != null) {
3068 //Log.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
3069 if (userLeaving) {
3070 performUserLeavingActivity(r);
3071 }
Bob Leee5408332009-09-04 18:31:17 -07003072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 r.activity.mConfigChangeFlags |= configChanges;
3074 Bundle state = performPauseActivity(token, finished, true);
3075
3076 // Tell the activity manager we have paused.
3077 try {
3078 ActivityManagerNative.getDefault().activityPaused(token, state);
3079 } catch (RemoteException ex) {
3080 }
3081 }
3082 }
3083
3084 final void performUserLeavingActivity(ActivityRecord r) {
3085 mInstrumentation.callActivityOnUserLeaving(r.activity);
3086 }
3087
3088 final Bundle performPauseActivity(IBinder token, boolean finished,
3089 boolean saveState) {
3090 ActivityRecord r = mActivities.get(token);
3091 return r != null ? performPauseActivity(r, finished, saveState) : null;
3092 }
3093
3094 final Bundle performPauseActivity(ActivityRecord r, boolean finished,
3095 boolean saveState) {
3096 if (r.paused) {
3097 if (r.activity.mFinished) {
3098 // If we are finishing, we won't call onResume() in certain cases.
3099 // So here we likewise don't want to call onPause() if the activity
3100 // isn't resumed.
3101 return null;
3102 }
3103 RuntimeException e = new RuntimeException(
3104 "Performing pause of activity that is not resumed: "
3105 + r.intent.getComponent().toShortString());
3106 Log.e(TAG, e.getMessage(), e);
3107 }
3108 Bundle state = null;
3109 if (finished) {
3110 r.activity.mFinished = true;
3111 }
3112 try {
3113 // Next have the activity save its current state and managed dialogs...
3114 if (!r.activity.mFinished && saveState) {
3115 state = new Bundle();
3116 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
3117 r.state = state;
3118 }
3119 // Now we are idle.
3120 r.activity.mCalled = false;
3121 mInstrumentation.callActivityOnPause(r.activity);
3122 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
3123 if (!r.activity.mCalled) {
3124 throw new SuperNotCalledException(
3125 "Activity " + r.intent.getComponent().toShortString() +
3126 " did not call through to super.onPause()");
3127 }
3128
3129 } catch (SuperNotCalledException e) {
3130 throw e;
3131
3132 } catch (Exception e) {
3133 if (!mInstrumentation.onException(r.activity, e)) {
3134 throw new RuntimeException(
3135 "Unable to pause activity "
3136 + r.intent.getComponent().toShortString()
3137 + ": " + e.toString(), e);
3138 }
3139 }
3140 r.paused = true;
3141 return state;
3142 }
3143
3144 final void performStopActivity(IBinder token) {
3145 ActivityRecord r = mActivities.get(token);
3146 performStopActivityInner(r, null, false);
3147 }
3148
3149 private static class StopInfo {
3150 Bitmap thumbnail;
3151 CharSequence description;
3152 }
3153
3154 private final class ProviderRefCount {
3155 public int count;
3156 ProviderRefCount(int pCount) {
3157 count = pCount;
3158 }
3159 }
3160
3161 private final void performStopActivityInner(ActivityRecord r,
3162 StopInfo info, boolean keepShown) {
3163 if (localLOGV) Log.v(TAG, "Performing stop of " + r);
3164 if (r != null) {
3165 if (!keepShown && r.stopped) {
3166 if (r.activity.mFinished) {
3167 // If we are finishing, we won't call onResume() in certain
3168 // cases. So here we likewise don't want to call onStop()
3169 // if the activity isn't resumed.
3170 return;
3171 }
3172 RuntimeException e = new RuntimeException(
3173 "Performing stop of activity that is not resumed: "
3174 + r.intent.getComponent().toShortString());
3175 Log.e(TAG, e.getMessage(), e);
3176 }
3177
3178 if (info != null) {
3179 try {
3180 // First create a thumbnail for the activity...
3181 //info.thumbnail = createThumbnailBitmap(r);
3182 info.description = r.activity.onCreateDescription();
3183 } catch (Exception e) {
3184 if (!mInstrumentation.onException(r.activity, e)) {
3185 throw new RuntimeException(
3186 "Unable to save state of activity "
3187 + r.intent.getComponent().toShortString()
3188 + ": " + e.toString(), e);
3189 }
3190 }
3191 }
3192
3193 if (!keepShown) {
3194 try {
3195 // Now we are idle.
3196 r.activity.performStop();
3197 } catch (Exception e) {
3198 if (!mInstrumentation.onException(r.activity, e)) {
3199 throw new RuntimeException(
3200 "Unable to stop activity "
3201 + r.intent.getComponent().toShortString()
3202 + ": " + e.toString(), e);
3203 }
3204 }
3205 r.stopped = true;
3206 }
3207
3208 r.paused = true;
3209 }
3210 }
3211
3212 private final void updateVisibility(ActivityRecord r, boolean show) {
3213 View v = r.activity.mDecor;
3214 if (v != null) {
3215 if (show) {
3216 if (!r.activity.mVisibleFromServer) {
3217 r.activity.mVisibleFromServer = true;
3218 mNumVisibleActivities++;
3219 if (r.activity.mVisibleFromClient) {
3220 r.activity.makeVisible();
3221 }
3222 }
3223 if (r.newConfig != null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003224 if (DEBUG_CONFIGURATION) Log.v(TAG, "Updating activity vis "
3225 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 performConfigurationChanged(r.activity, r.newConfig);
3227 r.newConfig = null;
3228 }
3229 } else {
3230 if (r.activity.mVisibleFromServer) {
3231 r.activity.mVisibleFromServer = false;
3232 mNumVisibleActivities--;
3233 v.setVisibility(View.INVISIBLE);
3234 }
3235 }
3236 }
3237 }
3238
3239 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
3240 ActivityRecord r = mActivities.get(token);
3241 r.activity.mConfigChangeFlags |= configChanges;
3242
3243 StopInfo info = new StopInfo();
3244 performStopActivityInner(r, info, show);
3245
3246 if (localLOGV) Log.v(
3247 TAG, "Finishing stop of " + r + ": show=" + show
3248 + " win=" + r.window);
3249
3250 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07003251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 // Tell activity manager we have been stopped.
3253 try {
3254 ActivityManagerNative.getDefault().activityStopped(
3255 r.token, info.thumbnail, info.description);
3256 } catch (RemoteException ex) {
3257 }
3258 }
3259
3260 final void performRestartActivity(IBinder token) {
3261 ActivityRecord r = mActivities.get(token);
3262 if (r.stopped) {
3263 r.activity.performRestart();
3264 r.stopped = false;
3265 }
3266 }
3267
3268 private final void handleWindowVisibility(IBinder token, boolean show) {
3269 ActivityRecord r = mActivities.get(token);
3270 if (!show && !r.stopped) {
3271 performStopActivityInner(r, null, show);
3272 } else if (show && r.stopped) {
3273 // If we are getting ready to gc after going to the background, well
3274 // we are back active so skip it.
3275 unscheduleGcIdler();
3276
3277 r.activity.performRestart();
3278 r.stopped = false;
3279 }
3280 if (r.activity.mDecor != null) {
3281 if (Config.LOGV) Log.v(
3282 TAG, "Handle window " + r + " visibility: " + show);
3283 updateVisibility(r, show);
3284 }
3285 }
3286
3287 private final void deliverResults(ActivityRecord r, List<ResultInfo> results) {
3288 final int N = results.size();
3289 for (int i=0; i<N; i++) {
3290 ResultInfo ri = results.get(i);
3291 try {
3292 if (ri.mData != null) {
3293 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3294 }
Chris Tate8a7dc172009-03-24 20:11:42 -07003295 if (DEBUG_RESULTS) Log.v(TAG,
3296 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 r.activity.dispatchActivityResult(ri.mResultWho,
3298 ri.mRequestCode, ri.mResultCode, ri.mData);
3299 } catch (Exception e) {
3300 if (!mInstrumentation.onException(r.activity, e)) {
3301 throw new RuntimeException(
3302 "Failure delivering result " + ri + " to activity "
3303 + r.intent.getComponent().toShortString()
3304 + ": " + e.toString(), e);
3305 }
3306 }
3307 }
3308 }
3309
3310 private final void handleSendResult(ResultData res) {
3311 ActivityRecord r = mActivities.get(res.token);
Chris Tate8a7dc172009-03-24 20:11:42 -07003312 if (DEBUG_RESULTS) Log.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 if (r != null) {
3314 final boolean resumed = !r.paused;
3315 if (!r.activity.mFinished && r.activity.mDecor != null
3316 && r.hideForNow && resumed) {
3317 // We had hidden the activity because it started another
3318 // one... we have gotten a result back and we are not
3319 // paused, so make sure our window is visible.
3320 updateVisibility(r, true);
3321 }
3322 if (resumed) {
3323 try {
3324 // Now we are idle.
3325 r.activity.mCalled = false;
3326 mInstrumentation.callActivityOnPause(r.activity);
3327 if (!r.activity.mCalled) {
3328 throw new SuperNotCalledException(
3329 "Activity " + r.intent.getComponent().toShortString()
3330 + " did not call through to super.onPause()");
3331 }
3332 } catch (SuperNotCalledException e) {
3333 throw e;
3334 } catch (Exception e) {
3335 if (!mInstrumentation.onException(r.activity, e)) {
3336 throw new RuntimeException(
3337 "Unable to pause activity "
3338 + r.intent.getComponent().toShortString()
3339 + ": " + e.toString(), e);
3340 }
3341 }
3342 }
3343 deliverResults(r, res.results);
3344 if (resumed) {
3345 mInstrumentation.callActivityOnResume(r.activity);
3346 }
3347 }
3348 }
3349
3350 public final ActivityRecord performDestroyActivity(IBinder token, boolean finishing) {
3351 return performDestroyActivity(token, finishing, 0, false);
3352 }
3353
3354 private final ActivityRecord performDestroyActivity(IBinder token, boolean finishing,
3355 int configChanges, boolean getNonConfigInstance) {
3356 ActivityRecord r = mActivities.get(token);
3357 if (localLOGV) Log.v(TAG, "Performing finish of " + r);
3358 if (r != null) {
3359 r.activity.mConfigChangeFlags |= configChanges;
3360 if (finishing) {
3361 r.activity.mFinished = true;
3362 }
3363 if (!r.paused) {
3364 try {
3365 r.activity.mCalled = false;
3366 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003367 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 r.activity.getComponentName().getClassName());
3369 if (!r.activity.mCalled) {
3370 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003371 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 + " did not call through to super.onPause()");
3373 }
3374 } catch (SuperNotCalledException e) {
3375 throw e;
3376 } catch (Exception e) {
3377 if (!mInstrumentation.onException(r.activity, e)) {
3378 throw new RuntimeException(
3379 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003380 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 + ": " + e.toString(), e);
3382 }
3383 }
3384 r.paused = true;
3385 }
3386 if (!r.stopped) {
3387 try {
3388 r.activity.performStop();
3389 } catch (SuperNotCalledException e) {
3390 throw e;
3391 } catch (Exception e) {
3392 if (!mInstrumentation.onException(r.activity, e)) {
3393 throw new RuntimeException(
3394 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003395 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 + ": " + e.toString(), e);
3397 }
3398 }
3399 r.stopped = true;
3400 }
3401 if (getNonConfigInstance) {
3402 try {
3403 r.lastNonConfigurationInstance
3404 = r.activity.onRetainNonConfigurationInstance();
3405 } catch (Exception e) {
3406 if (!mInstrumentation.onException(r.activity, e)) {
3407 throw new RuntimeException(
3408 "Unable to retain activity "
3409 + r.intent.getComponent().toShortString()
3410 + ": " + e.toString(), e);
3411 }
3412 }
3413 try {
3414 r.lastNonConfigurationChildInstances
3415 = r.activity.onRetainNonConfigurationChildInstances();
3416 } catch (Exception e) {
3417 if (!mInstrumentation.onException(r.activity, e)) {
3418 throw new RuntimeException(
3419 "Unable to retain child activities "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003420 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 + ": " + e.toString(), e);
3422 }
3423 }
Bob Leee5408332009-09-04 18:31:17 -07003424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 }
3426 try {
3427 r.activity.mCalled = false;
3428 r.activity.onDestroy();
3429 if (!r.activity.mCalled) {
3430 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003431 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 " did not call through to super.onDestroy()");
3433 }
3434 if (r.window != null) {
3435 r.window.closeAllPanels();
3436 }
3437 } catch (SuperNotCalledException e) {
3438 throw e;
3439 } catch (Exception e) {
3440 if (!mInstrumentation.onException(r.activity, e)) {
3441 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003442 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3443 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 }
3445 }
3446 }
3447 mActivities.remove(token);
3448
3449 return r;
3450 }
3451
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003452 private static String safeToComponentShortString(Intent intent) {
3453 ComponentName component = intent.getComponent();
3454 return component == null ? "[Unknown]" : component.toShortString();
3455 }
3456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 private final void handleDestroyActivity(IBinder token, boolean finishing,
3458 int configChanges, boolean getNonConfigInstance) {
3459 ActivityRecord r = performDestroyActivity(token, finishing,
3460 configChanges, getNonConfigInstance);
3461 if (r != null) {
3462 WindowManager wm = r.activity.getWindowManager();
3463 View v = r.activity.mDecor;
3464 if (v != null) {
3465 if (r.activity.mVisibleFromServer) {
3466 mNumVisibleActivities--;
3467 }
3468 IBinder wtoken = v.getWindowToken();
3469 if (r.activity.mWindowAdded) {
3470 wm.removeViewImmediate(v);
3471 }
3472 if (wtoken != null) {
3473 WindowManagerImpl.getDefault().closeAll(wtoken,
3474 r.activity.getClass().getName(), "Activity");
3475 }
3476 r.activity.mDecor = null;
3477 }
3478 WindowManagerImpl.getDefault().closeAll(token,
3479 r.activity.getClass().getName(), "Activity");
3480
3481 // Mocked out contexts won't be participating in the normal
3482 // process lifecycle, but if we're running with a proper
3483 // ApplicationContext we need to have it tear down things
3484 // cleanly.
3485 Context c = r.activity.getBaseContext();
3486 if (c instanceof ApplicationContext) {
3487 ((ApplicationContext) c).scheduleFinalCleanup(
3488 r.activity.getClass().getName(), "Activity");
3489 }
3490 }
3491 if (finishing) {
3492 try {
3493 ActivityManagerNative.getDefault().activityDestroyed(token);
3494 } catch (RemoteException ex) {
3495 // If the system process has died, it's game over for everyone.
3496 }
3497 }
3498 }
3499
3500 private final void handleRelaunchActivity(ActivityRecord tmp, int configChanges) {
3501 // If we are getting ready to gc after going to the background, well
3502 // we are back active so skip it.
3503 unscheduleGcIdler();
3504
3505 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07003506
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003507 if (DEBUG_CONFIGURATION) Log.v(TAG, "Relaunching activity "
3508 + tmp.token + " with configChanges=0x"
3509 + Integer.toHexString(configChanges));
3510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 // First: make sure we have the most recent configuration and most
3512 // recent version of the activity, or skip it if some previous call
3513 // had taken a more recent version.
3514 synchronized (mRelaunchingActivities) {
3515 int N = mRelaunchingActivities.size();
3516 IBinder token = tmp.token;
3517 tmp = null;
3518 for (int i=0; i<N; i++) {
3519 ActivityRecord r = mRelaunchingActivities.get(i);
3520 if (r.token == token) {
3521 tmp = r;
3522 mRelaunchingActivities.remove(i);
3523 i--;
3524 N--;
3525 }
3526 }
Bob Leee5408332009-09-04 18:31:17 -07003527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 if (tmp == null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003529 if (DEBUG_CONFIGURATION) Log.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 return;
3531 }
Bob Leee5408332009-09-04 18:31:17 -07003532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 if (mPendingConfiguration != null) {
3534 changedConfig = mPendingConfiguration;
3535 mPendingConfiguration = null;
3536 }
3537 }
Bob Leee5408332009-09-04 18:31:17 -07003538
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003539 if (DEBUG_CONFIGURATION) Log.v(TAG, "Relaunching activity "
3540 + tmp.token + ": changedConfig=" + changedConfig);
3541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 // If there was a pending configuration change, execute it first.
3543 if (changedConfig != null) {
3544 handleConfigurationChanged(changedConfig);
3545 }
Bob Leee5408332009-09-04 18:31:17 -07003546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 ActivityRecord r = mActivities.get(tmp.token);
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003548 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 if (r == null) {
3550 return;
3551 }
Bob Leee5408332009-09-04 18:31:17 -07003552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003554 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 Bundle savedState = null;
3557 if (!r.paused) {
3558 savedState = performPauseActivity(r.token, false, true);
3559 }
Bob Leee5408332009-09-04 18:31:17 -07003560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 r.activity = null;
3564 r.window = null;
3565 r.hideForNow = false;
3566 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003567 // Merge any pending results and pending intents; don't just replace them
3568 if (tmp.pendingResults != null) {
3569 if (r.pendingResults == null) {
3570 r.pendingResults = tmp.pendingResults;
3571 } else {
3572 r.pendingResults.addAll(tmp.pendingResults);
3573 }
3574 }
3575 if (tmp.pendingIntents != null) {
3576 if (r.pendingIntents == null) {
3577 r.pendingIntents = tmp.pendingIntents;
3578 } else {
3579 r.pendingIntents.addAll(tmp.pendingIntents);
3580 }
3581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 r.startsNotResumed = tmp.startsNotResumed;
3583 if (savedState != null) {
3584 r.state = savedState;
3585 }
Bob Leee5408332009-09-04 18:31:17 -07003586
Christopher Tateb70f3df2009-04-07 16:07:59 -07003587 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 }
3589
3590 private final void handleRequestThumbnail(IBinder token) {
3591 ActivityRecord r = mActivities.get(token);
3592 Bitmap thumbnail = createThumbnailBitmap(r);
3593 CharSequence description = null;
3594 try {
3595 description = r.activity.onCreateDescription();
3596 } catch (Exception e) {
3597 if (!mInstrumentation.onException(r.activity, e)) {
3598 throw new RuntimeException(
3599 "Unable to create description of activity "
3600 + r.intent.getComponent().toShortString()
3601 + ": " + e.toString(), e);
3602 }
3603 }
3604 //System.out.println("Reporting top thumbnail " + thumbnail);
3605 try {
3606 ActivityManagerNative.getDefault().reportThumbnail(
3607 token, thumbnail, description);
3608 } catch (RemoteException ex) {
3609 }
3610 }
3611
3612 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
3613 boolean allActivities, Configuration newConfig) {
3614 ArrayList<ComponentCallbacks> callbacks
3615 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 if (mActivities.size() > 0) {
3618 Iterator<ActivityRecord> it = mActivities.values().iterator();
3619 while (it.hasNext()) {
3620 ActivityRecord ar = it.next();
3621 Activity a = ar.activity;
3622 if (a != null) {
3623 if (!ar.activity.mFinished && (allActivities ||
3624 (a != null && !ar.paused))) {
3625 // If the activity is currently resumed, its configuration
3626 // needs to change right now.
3627 callbacks.add(a);
3628 } else if (newConfig != null) {
3629 // Otherwise, we will tell it about the change
3630 // the next time it is resumed or shown. Note that
3631 // the activity manager may, before then, decide the
3632 // activity needs to be destroyed to handle its new
3633 // configuration.
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003634 if (DEBUG_CONFIGURATION) Log.v(TAG, "Setting activity "
3635 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 ar.newConfig = newConfig;
3637 }
3638 }
3639 }
3640 }
3641 if (mServices.size() > 0) {
3642 Iterator<Service> it = mServices.values().iterator();
3643 while (it.hasNext()) {
3644 callbacks.add(it.next());
3645 }
3646 }
3647 synchronized (mProviderMap) {
3648 if (mLocalProviders.size() > 0) {
3649 Iterator<ProviderRecord> it = mLocalProviders.values().iterator();
3650 while (it.hasNext()) {
3651 callbacks.add(it.next().mLocalProvider);
3652 }
3653 }
3654 }
3655 final int N = mAllApplications.size();
3656 for (int i=0; i<N; i++) {
3657 callbacks.add(mAllApplications.get(i));
3658 }
Bob Leee5408332009-09-04 18:31:17 -07003659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 return callbacks;
3661 }
Bob Leee5408332009-09-04 18:31:17 -07003662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 private final void performConfigurationChanged(
3664 ComponentCallbacks cb, Configuration config) {
3665 // Only for Activity objects, check that they actually call up to their
3666 // superclass implementation. ComponentCallbacks is an interface, so
3667 // we check the runtime type and act accordingly.
3668 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3669 if (activity != null) {
3670 activity.mCalled = false;
3671 }
Bob Leee5408332009-09-04 18:31:17 -07003672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 boolean shouldChangeConfig = false;
3674 if ((activity == null) || (activity.mCurrentConfig == null)) {
3675 shouldChangeConfig = true;
3676 } else {
Bob Leee5408332009-09-04 18:31:17 -07003677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 // If the new config is the same as the config this Activity
3679 // is already running with then don't bother calling
3680 // onConfigurationChanged
3681 int diff = activity.mCurrentConfig.diff(config);
3682 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07003683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 // If this activity doesn't handle any of the config changes
3685 // then don't bother calling onConfigurationChanged as we're
3686 // going to destroy it.
3687 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
3688 shouldChangeConfig = true;
3689 }
3690 }
3691 }
Bob Leee5408332009-09-04 18:31:17 -07003692
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003693 if (DEBUG_CONFIGURATION) Log.v(TAG, "Config callback " + cb
3694 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 if (shouldChangeConfig) {
3696 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 if (activity != null) {
3699 if (!activity.mCalled) {
3700 throw new SuperNotCalledException(
3701 "Activity " + activity.getLocalClassName() +
3702 " did not call through to super.onConfigurationChanged()");
3703 }
3704 activity.mConfigChangeFlags = 0;
3705 activity.mCurrentConfig = new Configuration(config);
3706 }
3707 }
3708 }
3709
3710 final void handleConfigurationChanged(Configuration config) {
Bob Leee5408332009-09-04 18:31:17 -07003711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 synchronized (mRelaunchingActivities) {
3713 if (mPendingConfiguration != null) {
3714 config = mPendingConfiguration;
3715 mPendingConfiguration = null;
3716 }
3717 }
Bob Leee5408332009-09-04 18:31:17 -07003718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 ArrayList<ComponentCallbacks> callbacks
3720 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003721
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003722 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handle configuration changed: "
3723 + config);
3724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003725 synchronized(mPackages) {
3726 if (mConfiguration == null) {
3727 mConfiguration = new Configuration();
3728 }
3729 mConfiguration.updateFrom(config);
3730 DisplayMetrics dm = getDisplayMetricsLocked(true);
3731
3732 // set it for java, this also affects newly created Resources
3733 if (config.locale != null) {
3734 Locale.setDefault(config.locale);
3735 }
3736
Dianne Hackborn0d907fa2009-07-27 20:48:50 -07003737 Resources.updateSystemConfiguration(config, dm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738
3739 ApplicationContext.ApplicationPackageManager.configurationChanged();
3740 //Log.i(TAG, "Configuration changed in " + currentPackageName());
3741 {
3742 Iterator<WeakReference<Resources>> it =
3743 mActiveResources.values().iterator();
3744 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3745 // mActiveResources.entrySet().iterator();
3746 while (it.hasNext()) {
3747 WeakReference<Resources> v = it.next();
3748 Resources r = v.get();
3749 if (r != null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003750 r.updateConfiguration(config, dm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 //Log.i(TAG, "Updated app resources " + v.getKey()
3752 // + " " + r + ": " + r.getConfiguration());
3753 } else {
3754 //Log.i(TAG, "Removing old resources " + v.getKey());
3755 it.remove();
3756 }
3757 }
3758 }
Bob Leee5408332009-09-04 18:31:17 -07003759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 callbacks = collectComponentCallbacksLocked(false, config);
3761 }
Bob Leee5408332009-09-04 18:31:17 -07003762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 final int N = callbacks.size();
3764 for (int i=0; i<N; i++) {
3765 performConfigurationChanged(callbacks.get(i), config);
3766 }
3767 }
3768
3769 final void handleActivityConfigurationChanged(IBinder token) {
3770 ActivityRecord r = mActivities.get(token);
3771 if (r == null || r.activity == null) {
3772 return;
3773 }
Bob Leee5408332009-09-04 18:31:17 -07003774
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003775 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handle activity config changed: "
3776 + r.activityInfo.name);
3777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 performConfigurationChanged(r.activity, mConfiguration);
3779 }
3780
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003781 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003782 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003783 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003784 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3785 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003786 } catch (RuntimeException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003787 Log.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003788 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003789 } finally {
3790 try {
3791 pcd.fd.close();
3792 } catch (IOException e) {
3793 Log.w(TAG, "Failure closing profile fd", e);
3794 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003795 }
3796 } else {
3797 Debug.stopMethodTracing();
3798 }
3799 }
Bob Leee5408332009-09-04 18:31:17 -07003800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 final void handleLowMemory() {
3802 ArrayList<ComponentCallbacks> callbacks
3803 = new ArrayList<ComponentCallbacks>();
3804
3805 synchronized(mPackages) {
3806 callbacks = collectComponentCallbacksLocked(true, null);
3807 }
Bob Leee5408332009-09-04 18:31:17 -07003808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 final int N = callbacks.size();
3810 for (int i=0; i<N; i++) {
3811 callbacks.get(i).onLowMemory();
3812 }
3813
Chris Tatece229052009-03-25 16:44:52 -07003814 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3815 if (Process.myUid() != Process.SYSTEM_UID) {
3816 int sqliteReleased = SQLiteDatabase.releaseMemory();
3817 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3818 }
Bob Leee5408332009-09-04 18:31:17 -07003819
Mike Reedcaf0df12009-04-27 14:32:05 -04003820 // Ask graphics to free up as much as possible (font/image caches)
3821 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822
3823 BinderInternal.forceGc("mem");
3824 }
3825
3826 private final void handleBindApplication(AppBindData data) {
3827 mBoundApplication = data;
3828 mConfiguration = new Configuration(data.config);
3829
3830 // We now rely on this being set by zygote.
3831 //Process.setGid(data.appInfo.gid);
3832 //Process.setUid(data.appInfo.uid);
3833
3834 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003835 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 android.ddm.DdmHandleAppName.setAppName(data.processName);
3837
3838 /*
3839 * Before spawning a new process, reset the time zone to be the system time zone.
3840 * This needs to be done because the system time zone could have changed after the
3841 * the spawning of this process. Without doing this this process would have the incorrect
3842 * system time zone.
3843 */
3844 TimeZone.setDefault(null);
3845
3846 /*
3847 * Initialize the default locale in this process for the reasons we set the time zone.
3848 */
3849 Locale.setDefault(data.config.locale);
3850
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003851 /*
3852 * Update the system configuration since its preloaded and might not
3853 * reflect configuration changes. The configuration object passed
3854 * in AppBindData can be safely assumed to be up to date
3855 */
3856 Resources.getSystem().updateConfiguration(mConfiguration, null);
3857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 data.info = getPackageInfoNoCheck(data.appInfo);
3859
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003860 /**
3861 * Switch this process to density compatibility mode if needed.
3862 */
3863 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3864 == 0) {
3865 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3866 }
Bob Leee5408332009-09-04 18:31:17 -07003867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3869 // XXX should have option to change the port.
3870 Debug.changeDebugPort(8100);
3871 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
3872 Log.w(TAG, "Application " + data.info.getPackageName()
3873 + " is waiting for the debugger on port 8100...");
3874
3875 IActivityManager mgr = ActivityManagerNative.getDefault();
3876 try {
3877 mgr.showWaitingForDebugger(mAppThread, true);
3878 } catch (RemoteException ex) {
3879 }
3880
3881 Debug.waitForDebugger();
3882
3883 try {
3884 mgr.showWaitingForDebugger(mAppThread, false);
3885 } catch (RemoteException ex) {
3886 }
3887
3888 } else {
3889 Log.w(TAG, "Application " + data.info.getPackageName()
3890 + " can be debugged on port 8100...");
3891 }
3892 }
3893
3894 if (data.instrumentationName != null) {
3895 ApplicationContext appContext = new ApplicationContext();
3896 appContext.init(data.info, null, this);
3897 InstrumentationInfo ii = null;
3898 try {
3899 ii = appContext.getPackageManager().
3900 getInstrumentationInfo(data.instrumentationName, 0);
3901 } catch (PackageManager.NameNotFoundException e) {
3902 }
3903 if (ii == null) {
3904 throw new RuntimeException(
3905 "Unable to find instrumentation info for: "
3906 + data.instrumentationName);
3907 }
3908
3909 mInstrumentationAppDir = ii.sourceDir;
3910 mInstrumentationAppPackage = ii.packageName;
3911 mInstrumentedAppDir = data.info.getAppDir();
3912
3913 ApplicationInfo instrApp = new ApplicationInfo();
3914 instrApp.packageName = ii.packageName;
3915 instrApp.sourceDir = ii.sourceDir;
3916 instrApp.publicSourceDir = ii.publicSourceDir;
3917 instrApp.dataDir = ii.dataDir;
3918 PackageInfo pi = getPackageInfo(instrApp,
3919 appContext.getClassLoader(), false, true);
3920 ApplicationContext instrContext = new ApplicationContext();
3921 instrContext.init(pi, null, this);
3922
3923 try {
3924 java.lang.ClassLoader cl = instrContext.getClassLoader();
3925 mInstrumentation = (Instrumentation)
3926 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3927 } catch (Exception e) {
3928 throw new RuntimeException(
3929 "Unable to instantiate instrumentation "
3930 + data.instrumentationName + ": " + e.toString(), e);
3931 }
3932
3933 mInstrumentation.init(this, instrContext, appContext,
3934 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3935
3936 if (data.profileFile != null && !ii.handleProfiling) {
3937 data.handlingProfiling = true;
3938 File file = new File(data.profileFile);
3939 file.getParentFile().mkdirs();
3940 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3941 }
3942
3943 try {
3944 mInstrumentation.onCreate(data.instrumentationArgs);
3945 }
3946 catch (Exception e) {
3947 throw new RuntimeException(
3948 "Exception thrown in onCreate() of "
3949 + data.instrumentationName + ": " + e.toString(), e);
3950 }
3951
3952 } else {
3953 mInstrumentation = new Instrumentation();
3954 }
3955
Christopher Tate181fafa2009-05-14 11:12:14 -07003956 // If the app is being launched for full backup or restore, bring it up in
3957 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003958 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 mInitialApplication = app;
3960
3961 List<ProviderInfo> providers = data.providers;
3962 if (providers != null) {
3963 installContentProviders(app, providers);
3964 }
3965
3966 try {
3967 mInstrumentation.callApplicationOnCreate(app);
3968 } catch (Exception e) {
3969 if (!mInstrumentation.onException(app, e)) {
3970 throw new RuntimeException(
3971 "Unable to create application " + app.getClass().getName()
3972 + ": " + e.toString(), e);
3973 }
3974 }
3975 }
3976
3977 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3978 IActivityManager am = ActivityManagerNative.getDefault();
3979 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3980 Debug.stopMethodTracing();
3981 }
3982 //Log.i(TAG, "am: " + ActivityManagerNative.getDefault()
3983 // + ", app thr: " + mAppThread);
3984 try {
3985 am.finishInstrumentation(mAppThread, resultCode, results);
3986 } catch (RemoteException ex) {
3987 }
3988 }
3989
3990 private final void installContentProviders(
3991 Context context, List<ProviderInfo> providers) {
3992 final ArrayList<IActivityManager.ContentProviderHolder> results =
3993 new ArrayList<IActivityManager.ContentProviderHolder>();
3994
3995 Iterator<ProviderInfo> i = providers.iterator();
3996 while (i.hasNext()) {
3997 ProviderInfo cpi = i.next();
3998 StringBuilder buf = new StringBuilder(128);
3999 buf.append("Publishing provider ");
4000 buf.append(cpi.authority);
4001 buf.append(": ");
4002 buf.append(cpi.name);
4003 Log.i(TAG, buf.toString());
4004 IContentProvider cp = installProvider(context, null, cpi, false);
4005 if (cp != null) {
4006 IActivityManager.ContentProviderHolder cph =
4007 new IActivityManager.ContentProviderHolder(cpi);
4008 cph.provider = cp;
4009 results.add(cph);
4010 // Don't ever unload this provider from the process.
4011 synchronized(mProviderMap) {
4012 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
4013 }
4014 }
4015 }
4016
4017 try {
4018 ActivityManagerNative.getDefault().publishContentProviders(
4019 getApplicationThread(), results);
4020 } catch (RemoteException ex) {
4021 }
4022 }
4023
4024 private final IContentProvider getProvider(Context context, String name) {
4025 synchronized(mProviderMap) {
4026 final ProviderRecord pr = mProviderMap.get(name);
4027 if (pr != null) {
4028 return pr.mProvider;
4029 }
4030 }
4031
4032 IActivityManager.ContentProviderHolder holder = null;
4033 try {
4034 holder = ActivityManagerNative.getDefault().getContentProvider(
4035 getApplicationThread(), name);
4036 } catch (RemoteException ex) {
4037 }
4038 if (holder == null) {
4039 Log.e(TAG, "Failed to find provider info for " + name);
4040 return null;
4041 }
4042 if (holder.permissionFailure != null) {
4043 throw new SecurityException("Permission " + holder.permissionFailure
4044 + " required for provider " + name);
4045 }
4046
4047 IContentProvider prov = installProvider(context, holder.provider,
4048 holder.info, true);
4049 //Log.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
4050 if (holder.noReleaseNeeded || holder.provider == null) {
4051 // We are not going to release the provider if it is an external
4052 // provider that doesn't care about being released, or if it is
4053 // a local provider running in this process.
4054 //Log.i(TAG, "*** NO RELEASE NEEDED");
4055 synchronized(mProviderMap) {
4056 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
4057 }
4058 }
4059 return prov;
4060 }
4061
4062 public final IContentProvider acquireProvider(Context c, String name) {
4063 IContentProvider provider = getProvider(c, name);
4064 if(provider == null)
4065 return null;
4066 IBinder jBinder = provider.asBinder();
4067 synchronized(mProviderMap) {
4068 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4069 if(prc == null) {
4070 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4071 } else {
4072 prc.count++;
4073 } //end else
4074 } //end synchronized
4075 return provider;
4076 }
4077
4078 public final boolean releaseProvider(IContentProvider provider) {
4079 if(provider == null) {
4080 return false;
4081 }
4082 IBinder jBinder = provider.asBinder();
4083 synchronized(mProviderMap) {
4084 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4085 if(prc == null) {
4086 if(localLOGV) Log.v(TAG, "releaseProvider::Weird shouldnt be here");
4087 return false;
4088 } else {
4089 prc.count--;
4090 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004091 // Schedule the actual remove asynchronously, since we
4092 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004093 // TODO: it would be nice to post a delayed message, so
4094 // if we come back and need the same provider quickly
4095 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004096 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4097 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 } //end if
4099 } //end else
4100 } //end synchronized
4101 return true;
4102 }
4103
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004104 final void completeRemoveProvider(IContentProvider provider) {
4105 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004106 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004107 synchronized(mProviderMap) {
4108 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4109 if(prc != null && prc.count == 0) {
4110 mProviderRefCountMap.remove(jBinder);
4111 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004112 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004113 }
4114 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004115
4116 if (name != null) {
4117 try {
4118 if(localLOGV) Log.v(TAG, "removeProvider::Invoking " +
4119 "ActivityManagerNative.removeContentProvider(" + name);
4120 ActivityManagerNative.getDefault().removeContentProvider(
4121 getApplicationThread(), name);
4122 } catch (RemoteException e) {
4123 //do nothing content provider object is dead any way
4124 } //end catch
4125 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004126 }
4127
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004128 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004130 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 }
4132 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004134 String name = null;
4135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 // remove the provider from mProviderMap
4137 Iterator<ProviderRecord> iter = mProviderMap.values().iterator();
4138 while (iter.hasNext()) {
4139 ProviderRecord pr = iter.next();
4140 IBinder myBinder = pr.mProvider.asBinder();
4141 if (myBinder == providerBinder) {
4142 //find if its published by this process itself
4143 if(pr.mLocalProvider != null) {
4144 if(localLOGV) Log.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004145 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 }
4147 if(localLOGV) Log.v(TAG, "removeProvider::Not local provider Unlinking " +
4148 "death recipient");
4149 //content provider is in another process
4150 myBinder.unlinkToDeath(pr, 0);
4151 iter.remove();
4152 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004153 if(name == null) {
4154 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
4156 } //end if myBinder
4157 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004158
4159 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 }
4161
4162 final void removeDeadProvider(String name, IContentProvider provider) {
4163 synchronized(mProviderMap) {
4164 ProviderRecord pr = mProviderMap.get(name);
4165 if (pr.mProvider.asBinder() == provider.asBinder()) {
4166 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004167 ProviderRecord removed = mProviderMap.remove(name);
4168 if (removed != null) {
4169 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 }
4172 }
4173 }
4174
4175 final void removeDeadProviderLocked(String name, IContentProvider provider) {
4176 ProviderRecord pr = mProviderMap.get(name);
4177 if (pr.mProvider.asBinder() == provider.asBinder()) {
4178 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004179 ProviderRecord removed = mProviderMap.remove(name);
4180 if (removed != null) {
4181 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 }
4184 }
4185
4186 private final IContentProvider installProvider(Context context,
4187 IContentProvider provider, ProviderInfo info, boolean noisy) {
4188 ContentProvider localProvider = null;
4189 if (provider == null) {
4190 if (noisy) {
4191 Log.d(TAG, "Loading provider " + info.authority + ": "
4192 + info.name);
4193 }
4194 Context c = null;
4195 ApplicationInfo ai = info.applicationInfo;
4196 if (context.getPackageName().equals(ai.packageName)) {
4197 c = context;
4198 } else if (mInitialApplication != null &&
4199 mInitialApplication.getPackageName().equals(ai.packageName)) {
4200 c = mInitialApplication;
4201 } else {
4202 try {
4203 c = context.createPackageContext(ai.packageName,
4204 Context.CONTEXT_INCLUDE_CODE);
4205 } catch (PackageManager.NameNotFoundException e) {
4206 }
4207 }
4208 if (c == null) {
4209 Log.w(TAG, "Unable to get context for package " +
4210 ai.packageName +
4211 " while loading content provider " +
4212 info.name);
4213 return null;
4214 }
4215 try {
4216 final java.lang.ClassLoader cl = c.getClassLoader();
4217 localProvider = (ContentProvider)cl.
4218 loadClass(info.name).newInstance();
4219 provider = localProvider.getIContentProvider();
4220 if (provider == null) {
4221 Log.e(TAG, "Failed to instantiate class " +
4222 info.name + " from sourceDir " +
4223 info.applicationInfo.sourceDir);
4224 return null;
4225 }
4226 if (Config.LOGV) Log.v(
4227 TAG, "Instantiating local provider " + info.name);
4228 // XXX Need to create the correct context for this provider.
4229 localProvider.attachInfo(c, info);
4230 } catch (java.lang.Exception e) {
4231 if (!mInstrumentation.onException(null, e)) {
4232 throw new RuntimeException(
4233 "Unable to get provider " + info.name
4234 + ": " + e.toString(), e);
4235 }
4236 return null;
4237 }
4238 } else if (localLOGV) {
4239 Log.v(TAG, "Installing external provider " + info.authority + ": "
4240 + info.name);
4241 }
4242
4243 synchronized (mProviderMap) {
4244 // Cache the pointer for the remote provider.
4245 String names[] = PATTERN_SEMICOLON.split(info.authority);
4246 for (int i=0; i<names.length; i++) {
4247 ProviderRecord pr = new ProviderRecord(names[i], provider,
4248 localProvider);
4249 try {
4250 provider.asBinder().linkToDeath(pr, 0);
4251 mProviderMap.put(names[i], pr);
4252 } catch (RemoteException e) {
4253 return null;
4254 }
4255 }
4256 if (localProvider != null) {
4257 mLocalProviders.put(provider.asBinder(),
4258 new ProviderRecord(null, provider, localProvider));
4259 }
4260 }
4261
4262 return provider;
4263 }
4264
4265 private final void attach(boolean system) {
4266 sThreadLocal.set(this);
4267 mSystemThread = system;
4268 AndroidHttpClient.setThreadBlocked(true);
4269 if (!system) {
4270 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4271 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4272 IActivityManager mgr = ActivityManagerNative.getDefault();
4273 try {
4274 mgr.attachApplication(mAppThread);
4275 } catch (RemoteException ex) {
4276 }
4277 } else {
4278 // Don't set application object here -- if the system crashes,
4279 // we can't display an alert, we just want to die die die.
4280 android.ddm.DdmHandleAppName.setAppName("system_process");
4281 try {
4282 mInstrumentation = new Instrumentation();
4283 ApplicationContext context = new ApplicationContext();
4284 context.init(getSystemContext().mPackageInfo, null, this);
4285 Application app = Instrumentation.newApplication(Application.class, context);
4286 mAllApplications.add(app);
4287 mInitialApplication = app;
4288 app.onCreate();
4289 } catch (Exception e) {
4290 throw new RuntimeException(
4291 "Unable to instantiate Application():" + e.toString(), e);
4292 }
4293 }
4294 }
4295
4296 private final void detach()
4297 {
4298 AndroidHttpClient.setThreadBlocked(false);
4299 sThreadLocal.set(null);
4300 }
4301
4302 public static final ActivityThread systemMain() {
4303 ActivityThread thread = new ActivityThread();
4304 thread.attach(true);
4305 return thread;
4306 }
4307
4308 public final void installSystemProviders(List providers) {
4309 if (providers != null) {
4310 installContentProviders(mInitialApplication,
4311 (List<ProviderInfo>)providers);
4312 }
4313 }
4314
4315 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004316 SamplingProfilerIntegration.start();
4317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 Process.setArgV0("<pre-initialized>");
4319
4320 Looper.prepareMainLooper();
4321
4322 ActivityThread thread = new ActivityThread();
4323 thread.attach(false);
4324
4325 Looper.loop();
4326
4327 if (Process.supportsProcesses()) {
4328 throw new RuntimeException("Main thread loop unexpectedly exited");
4329 }
4330
4331 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02004332 String name = (thread.mInitialApplication != null)
4333 ? thread.mInitialApplication.getPackageName()
4334 : "<unknown>";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 Log.i(TAG, "Main thread of " + name + " is now exiting");
4336 }
4337}