blob: 909620d21dca14d581974791192d68d7248325d0 [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) {
Dianne Hackbornf9315202009-11-17 18:28:55 -0800181 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
182 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 synchronized (mPackages) {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700184 // Resources is app scale dependent.
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700185 if (false) {
186 Log.w(TAG, "getTopLevelResources: " + resDir + " / "
187 + compInfo.applicationScale);
188 }
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700189 WeakReference<Resources> wr = mActiveResources.get(key);
Dianne Hackbornf9315202009-11-17 18:28:55 -0800190 r = wr != null ? wr.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 if (r != null && r.getAssets().isUpToDate()) {
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700192 if (false) {
193 Log.w(TAG, "Returning cached resources " + r + " " + resDir
194 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 return r;
197 }
Dianne Hackbornf9315202009-11-17 18:28:55 -0800198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
Dianne Hackbornf9315202009-11-17 18:28:55 -0800200 //if (r != null) {
201 // Log.w(TAG, "Throwing away out-of-date resources!!!! "
202 // + r + " " + resDir);
203 //}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Dianne Hackbornf9315202009-11-17 18:28:55 -0800205 AssetManager assets = new AssetManager();
206 if (assets.addAssetPath(resDir) == 0) {
207 return null;
208 }
209
210 //Log.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
211 DisplayMetrics metrics = getDisplayMetricsLocked(false);
212 r = new Resources(assets, metrics, getConfiguration(), compInfo);
213 if (false) {
214 Log.i(TAG, "Created app resources " + resDir + " " + r + ": "
215 + r.getConfiguration() + " appScale="
216 + r.getCompatibilityInfo().applicationScale);
217 }
218
219 synchronized (mPackages) {
220 WeakReference<Resources> wr = mActiveResources.get(key);
221 Resources existing = wr != null ? wr.get() : null;
222 if (existing != null && existing.getAssets().isUpToDate()) {
223 // Someone else already created the resources while we were
224 // unlocked; go ahead and use theirs.
225 r.getAssets().close();
226 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 }
Dianne Hackbornf9315202009-11-17 18:28:55 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // XXX need to remove entries when weak references go away
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700230 mActiveResources.put(key, new WeakReference<Resources>(r));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 return r;
232 }
233 }
234
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700235 /**
236 * Creates the top level resources for the given package.
237 */
238 Resources getTopLevelResources(String resDir, PackageInfo pkgInfo) {
239 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
240 }
241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 final Handler getHandler() {
243 return mH;
244 }
245
246 public final static class PackageInfo {
247
248 private final ActivityThread mActivityThread;
249 private final ApplicationInfo mApplicationInfo;
250 private final String mPackageName;
251 private final String mAppDir;
252 private final String mResDir;
253 private final String[] mSharedLibraries;
254 private final String mDataDir;
255 private final File mDataDirFile;
256 private final ClassLoader mBaseClassLoader;
257 private final boolean mSecurityViolation;
258 private final boolean mIncludeCode;
259 private Resources mResources;
260 private ClassLoader mClassLoader;
261 private Application mApplication;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700262 private CompatibilityInfo mCompatibilityInfo;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mReceivers
265 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
266 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mUnregisteredReceivers
267 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
268 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mServices
269 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
270 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mUnboundServices
271 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
272
273 int mClientCount = 0;
274
275 public PackageInfo(ActivityThread activityThread, ApplicationInfo aInfo,
276 ActivityThread mainThread, ClassLoader baseLoader,
277 boolean securityViolation, boolean includeCode) {
278 mActivityThread = activityThread;
279 mApplicationInfo = aInfo;
280 mPackageName = aInfo.packageName;
281 mAppDir = aInfo.sourceDir;
282 mResDir = aInfo.uid == Process.myUid() ? aInfo.sourceDir
283 : aInfo.publicSourceDir;
284 mSharedLibraries = aInfo.sharedLibraryFiles;
285 mDataDir = aInfo.dataDir;
286 mDataDirFile = mDataDir != null ? new File(mDataDir) : null;
287 mBaseClassLoader = baseLoader;
288 mSecurityViolation = securityViolation;
289 mIncludeCode = includeCode;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700290 mCompatibilityInfo = new CompatibilityInfo(aInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291
292 if (mAppDir == null) {
293 if (mSystemContext == null) {
294 mSystemContext =
295 ApplicationContext.createSystemContext(mainThread);
296 mSystemContext.getResources().updateConfiguration(
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700297 mainThread.getConfiguration(),
298 mainThread.getDisplayMetricsLocked(false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 //Log.i(TAG, "Created system resources "
300 // + mSystemContext.getResources() + ": "
301 // + mSystemContext.getResources().getConfiguration());
302 }
303 mClassLoader = mSystemContext.getClassLoader();
304 mResources = mSystemContext.getResources();
305 }
306 }
307
308 public PackageInfo(ActivityThread activityThread, String name,
Mike Cleron432b7132009-09-24 15:28:29 -0700309 Context systemContext, ApplicationInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 mActivityThread = activityThread;
Mike Cleron432b7132009-09-24 15:28:29 -0700311 mApplicationInfo = info != null ? info : new ApplicationInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 mApplicationInfo.packageName = name;
313 mPackageName = name;
314 mAppDir = null;
315 mResDir = null;
316 mSharedLibraries = null;
317 mDataDir = null;
318 mDataDirFile = null;
319 mBaseClassLoader = null;
320 mSecurityViolation = false;
321 mIncludeCode = true;
322 mClassLoader = systemContext.getClassLoader();
323 mResources = systemContext.getResources();
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700324 mCompatibilityInfo = new CompatibilityInfo(mApplicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 }
326
327 public String getPackageName() {
328 return mPackageName;
329 }
330
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700331 public ApplicationInfo getApplicationInfo() {
332 return mApplicationInfo;
333 }
Bob Leee5408332009-09-04 18:31:17 -0700334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 public boolean isSecurityViolation() {
336 return mSecurityViolation;
337 }
338
339 /**
340 * Gets the array of shared libraries that are listed as
341 * used by the given package.
Bob Leee5408332009-09-04 18:31:17 -0700342 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 * @param packageName the name of the package (note: not its
344 * file name)
345 * @return null-ok; the array of shared libraries, each one
346 * a fully-qualified path
347 */
348 private static String[] getLibrariesFor(String packageName) {
349 ApplicationInfo ai = null;
350 try {
351 ai = getPackageManager().getApplicationInfo(packageName,
352 PackageManager.GET_SHARED_LIBRARY_FILES);
353 } catch (RemoteException e) {
354 throw new AssertionError(e);
355 }
356
357 if (ai == null) {
358 return null;
359 }
360
361 return ai.sharedLibraryFiles;
362 }
363
364 /**
365 * Combines two arrays (of library names) such that they are
366 * concatenated in order but are devoid of duplicates. The
367 * result is a single string with the names of the libraries
368 * separated by colons, or <code>null</code> if both lists
369 * were <code>null</code> or empty.
Bob Leee5408332009-09-04 18:31:17 -0700370 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 * @param list1 null-ok; the first list
372 * @param list2 null-ok; the second list
373 * @return null-ok; the combination
374 */
375 private static String combineLibs(String[] list1, String[] list2) {
376 StringBuilder result = new StringBuilder(300);
377 boolean first = true;
378
379 if (list1 != null) {
380 for (String s : list1) {
381 if (first) {
382 first = false;
383 } else {
384 result.append(':');
385 }
386 result.append(s);
387 }
388 }
389
390 // Only need to check for duplicates if list1 was non-empty.
391 boolean dupCheck = !first;
392
393 if (list2 != null) {
394 for (String s : list2) {
395 if (dupCheck && ArrayUtils.contains(list1, s)) {
396 continue;
397 }
Bob Leee5408332009-09-04 18:31:17 -0700398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 if (first) {
400 first = false;
401 } else {
402 result.append(':');
403 }
404 result.append(s);
405 }
406 }
407
408 return result.toString();
409 }
Bob Leee5408332009-09-04 18:31:17 -0700410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 public ClassLoader getClassLoader() {
412 synchronized (this) {
413 if (mClassLoader != null) {
414 return mClassLoader;
415 }
416
417 if (mIncludeCode && !mPackageName.equals("android")) {
418 String zip = mAppDir;
419
420 /*
421 * The following is a bit of a hack to inject
422 * instrumentation into the system: If the app
423 * being started matches one of the instrumentation names,
424 * then we combine both the "instrumentation" and
425 * "instrumented" app into the path, along with the
426 * concatenation of both apps' shared library lists.
427 */
428
429 String instrumentationAppDir =
430 mActivityThread.mInstrumentationAppDir;
431 String instrumentationAppPackage =
432 mActivityThread.mInstrumentationAppPackage;
433 String instrumentedAppDir =
434 mActivityThread.mInstrumentedAppDir;
435 String[] instrumentationLibs = null;
436
437 if (mAppDir.equals(instrumentationAppDir)
438 || mAppDir.equals(instrumentedAppDir)) {
439 zip = instrumentationAppDir + ":" + instrumentedAppDir;
440 if (! instrumentedAppDir.equals(instrumentationAppDir)) {
441 instrumentationLibs =
442 getLibrariesFor(instrumentationAppPackage);
443 }
444 }
445
446 if ((mSharedLibraries != null) ||
447 (instrumentationLibs != null)) {
Bob Leee5408332009-09-04 18:31:17 -0700448 zip =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 combineLibs(mSharedLibraries, instrumentationLibs)
450 + ':' + zip;
451 }
452
453 /*
454 * With all the combination done (if necessary, actually
455 * create the class loader.
456 */
457
458 if (localLOGV) Log.v(TAG, "Class path: " + zip);
459
460 mClassLoader =
461 ApplicationLoaders.getDefault().getClassLoader(
462 zip, mDataDir, mBaseClassLoader);
463 } else {
464 if (mBaseClassLoader == null) {
465 mClassLoader = ClassLoader.getSystemClassLoader();
466 } else {
467 mClassLoader = mBaseClassLoader;
468 }
469 }
470 return mClassLoader;
471 }
472 }
473
474 public String getAppDir() {
475 return mAppDir;
476 }
477
478 public String getResDir() {
479 return mResDir;
480 }
481
482 public String getDataDir() {
483 return mDataDir;
484 }
485
486 public File getDataDirFile() {
487 return mDataDirFile;
488 }
489
490 public AssetManager getAssets(ActivityThread mainThread) {
491 return getResources(mainThread).getAssets();
492 }
493
494 public Resources getResources(ActivityThread mainThread) {
495 if (mResources == null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700496 mResources = mainThread.getTopLevelResources(mResDir, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 }
498 return mResources;
499 }
500
Dianne Hackborn0be1f782009-11-09 12:30:12 -0800501 public Application makeApplication(boolean forceDefaultAppClass,
502 Instrumentation instrumentation) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 if (mApplication != null) {
504 return mApplication;
505 }
Bob Leee5408332009-09-04 18:31:17 -0700506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 Application app = null;
Bob Leee5408332009-09-04 18:31:17 -0700508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 String appClass = mApplicationInfo.className;
Christopher Tate181fafa2009-05-14 11:12:14 -0700510 if (forceDefaultAppClass || (appClass == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 appClass = "android.app.Application";
512 }
513
514 try {
515 java.lang.ClassLoader cl = getClassLoader();
516 ApplicationContext appContext = new ApplicationContext();
517 appContext.init(this, null, mActivityThread);
518 app = mActivityThread.mInstrumentation.newApplication(
519 cl, appClass, appContext);
520 appContext.setOuterContext(app);
521 } catch (Exception e) {
522 if (!mActivityThread.mInstrumentation.onException(app, e)) {
523 throw new RuntimeException(
524 "Unable to instantiate application " + appClass
525 + ": " + e.toString(), e);
526 }
527 }
528 mActivityThread.mAllApplications.add(app);
Dianne Hackborn0be1f782009-11-09 12:30:12 -0800529 mApplication = app;
530
531 if (instrumentation != null) {
532 try {
533 instrumentation.callApplicationOnCreate(app);
534 } catch (Exception e) {
535 if (!instrumentation.onException(app, e)) {
536 throw new RuntimeException(
537 "Unable to create application " + app.getClass().getName()
538 + ": " + e.toString(), e);
539 }
540 }
541 }
542
543 return app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 }
Bob Leee5408332009-09-04 18:31:17 -0700545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 public void removeContextRegistrations(Context context,
547 String who, String what) {
548 HashMap<BroadcastReceiver, ReceiverDispatcher> rmap =
549 mReceivers.remove(context);
550 if (rmap != null) {
551 Iterator<ReceiverDispatcher> it = rmap.values().iterator();
552 while (it.hasNext()) {
553 ReceiverDispatcher rd = it.next();
554 IntentReceiverLeaked leak = new IntentReceiverLeaked(
555 what + " " + who + " has leaked IntentReceiver "
556 + rd.getIntentReceiver() + " that was " +
557 "originally registered here. Are you missing a " +
558 "call to unregisterReceiver()?");
559 leak.setStackTrace(rd.getLocation().getStackTrace());
560 Log.e(TAG, leak.getMessage(), leak);
561 try {
562 ActivityManagerNative.getDefault().unregisterReceiver(
563 rd.getIIntentReceiver());
564 } catch (RemoteException e) {
565 // system crashed, nothing we can do
566 }
567 }
568 }
569 mUnregisteredReceivers.remove(context);
570 //Log.i(TAG, "Receiver registrations: " + mReceivers);
571 HashMap<ServiceConnection, ServiceDispatcher> smap =
572 mServices.remove(context);
573 if (smap != null) {
574 Iterator<ServiceDispatcher> it = smap.values().iterator();
575 while (it.hasNext()) {
576 ServiceDispatcher sd = it.next();
577 ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
578 what + " " + who + " has leaked ServiceConnection "
579 + sd.getServiceConnection() + " that was originally bound here");
580 leak.setStackTrace(sd.getLocation().getStackTrace());
581 Log.e(TAG, leak.getMessage(), leak);
582 try {
583 ActivityManagerNative.getDefault().unbindService(
584 sd.getIServiceConnection());
585 } catch (RemoteException e) {
586 // system crashed, nothing we can do
587 }
588 sd.doForget();
589 }
590 }
591 mUnboundServices.remove(context);
592 //Log.i(TAG, "Service registrations: " + mServices);
593 }
594
595 public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,
596 Context context, Handler handler,
597 Instrumentation instrumentation, boolean registered) {
598 synchronized (mReceivers) {
599 ReceiverDispatcher rd = null;
600 HashMap<BroadcastReceiver, ReceiverDispatcher> map = null;
601 if (registered) {
602 map = mReceivers.get(context);
603 if (map != null) {
604 rd = map.get(r);
605 }
606 }
607 if (rd == null) {
608 rd = new ReceiverDispatcher(r, context, handler,
609 instrumentation, registered);
610 if (registered) {
611 if (map == null) {
612 map = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
613 mReceivers.put(context, map);
614 }
615 map.put(r, rd);
616 }
617 } else {
618 rd.validate(context, handler);
619 }
620 return rd.getIIntentReceiver();
621 }
622 }
623
624 public IIntentReceiver forgetReceiverDispatcher(Context context,
625 BroadcastReceiver r) {
626 synchronized (mReceivers) {
627 HashMap<BroadcastReceiver, ReceiverDispatcher> map = mReceivers.get(context);
628 ReceiverDispatcher rd = null;
629 if (map != null) {
630 rd = map.get(r);
631 if (rd != null) {
632 map.remove(r);
633 if (map.size() == 0) {
634 mReceivers.remove(context);
635 }
636 if (r.getDebugUnregister()) {
637 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
638 = mUnregisteredReceivers.get(context);
639 if (holder == null) {
640 holder = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
641 mUnregisteredReceivers.put(context, holder);
642 }
643 RuntimeException ex = new IllegalArgumentException(
644 "Originally unregistered here:");
645 ex.fillInStackTrace();
646 rd.setUnregisterLocation(ex);
647 holder.put(r, rd);
648 }
649 return rd.getIIntentReceiver();
650 }
651 }
652 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
653 = mUnregisteredReceivers.get(context);
654 if (holder != null) {
655 rd = holder.get(r);
656 if (rd != null) {
657 RuntimeException ex = rd.getUnregisterLocation();
658 throw new IllegalArgumentException(
659 "Unregistering Receiver " + r
660 + " that was already unregistered", ex);
661 }
662 }
663 if (context == null) {
664 throw new IllegalStateException("Unbinding Receiver " + r
665 + " from Context that is no longer in use: " + context);
666 } else {
667 throw new IllegalArgumentException("Receiver not registered: " + r);
668 }
669
670 }
671 }
672
673 static final class ReceiverDispatcher {
674
675 final static class InnerReceiver extends IIntentReceiver.Stub {
676 final WeakReference<ReceiverDispatcher> mDispatcher;
677 final ReceiverDispatcher mStrongRef;
Bob Leee5408332009-09-04 18:31:17 -0700678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 InnerReceiver(ReceiverDispatcher rd, boolean strong) {
680 mDispatcher = new WeakReference<ReceiverDispatcher>(rd);
681 mStrongRef = strong ? rd : null;
682 }
683 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700684 String data, Bundle extras, boolean ordered, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 ReceiverDispatcher rd = mDispatcher.get();
686 if (DEBUG_BROADCAST) {
687 int seq = intent.getIntExtra("seq", -1);
688 Log.i(TAG, "Receiving broadcast " + intent.getAction() + " seq=" + seq
689 + " to " + rd);
690 }
691 if (rd != null) {
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700692 rd.performReceive(intent, resultCode, data, extras,
693 ordered, sticky);
Christopher Tate08a46252009-12-08 13:48:45 -0800694 } else {
695 // The activity manager dispatched a broadcast to a registered
696 // receiver in this process, but before it could be delivered the
697 // receiver was unregistered. Acknowledge the broadcast on its
698 // behalf so that the system's broadcast sequence can continue.
699 if (DEBUG_BROADCAST) {
700 Log.i(TAG, "Broadcast to unregistered receiver");
701 }
702 IActivityManager mgr = ActivityManagerNative.getDefault();
703 try {
704 mgr.finishReceiver(this, resultCode, data, extras, false);
705 } catch (RemoteException e) {
706 Log.w(TAG, "Couldn't finish broadcast to unregistered receiver");
707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 }
709 }
710 }
Bob Leee5408332009-09-04 18:31:17 -0700711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 final IIntentReceiver.Stub mIIntentReceiver;
713 final BroadcastReceiver mReceiver;
714 final Context mContext;
715 final Handler mActivityThread;
716 final Instrumentation mInstrumentation;
717 final boolean mRegistered;
718 final IntentReceiverLeaked mLocation;
719 RuntimeException mUnregisterLocation;
720
721 final class Args implements Runnable {
722 private Intent mCurIntent;
723 private int mCurCode;
724 private String mCurData;
725 private Bundle mCurMap;
726 private boolean mCurOrdered;
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700727 private boolean mCurSticky;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728
729 public void run() {
730 BroadcastReceiver receiver = mReceiver;
731 if (DEBUG_BROADCAST) {
732 int seq = mCurIntent.getIntExtra("seq", -1);
Christopher Tate08a46252009-12-08 13:48:45 -0800733 Log.i(TAG, "Dispatching broadcast " + mCurIntent.getAction()
734 + " seq=" + seq + " to " + mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 }
736 if (receiver == null) {
737 return;
738 }
739
740 IActivityManager mgr = ActivityManagerNative.getDefault();
741 Intent intent = mCurIntent;
742 mCurIntent = null;
743 try {
744 ClassLoader cl = mReceiver.getClass().getClassLoader();
745 intent.setExtrasClassLoader(cl);
746 if (mCurMap != null) {
747 mCurMap.setClassLoader(cl);
748 }
749 receiver.setOrderedHint(true);
750 receiver.setResult(mCurCode, mCurData, mCurMap);
751 receiver.clearAbortBroadcast();
752 receiver.setOrderedHint(mCurOrdered);
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700753 receiver.setInitialStickyHint(mCurSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 receiver.onReceive(mContext, intent);
755 } catch (Exception e) {
756 if (mRegistered && mCurOrdered) {
757 try {
758 mgr.finishReceiver(mIIntentReceiver,
759 mCurCode, mCurData, mCurMap, false);
760 } catch (RemoteException ex) {
761 }
762 }
763 if (mInstrumentation == null ||
764 !mInstrumentation.onException(mReceiver, e)) {
765 throw new RuntimeException(
766 "Error receiving broadcast " + intent
767 + " in " + mReceiver, e);
768 }
769 }
770 if (mRegistered && mCurOrdered) {
771 try {
772 mgr.finishReceiver(mIIntentReceiver,
773 receiver.getResultCode(),
774 receiver.getResultData(),
775 receiver.getResultExtras(false),
776 receiver.getAbortBroadcast());
777 } catch (RemoteException ex) {
778 }
779 }
780 }
781 }
782
783 ReceiverDispatcher(BroadcastReceiver receiver, Context context,
784 Handler activityThread, Instrumentation instrumentation,
785 boolean registered) {
786 if (activityThread == null) {
787 throw new NullPointerException("Handler must not be null");
788 }
789
790 mIIntentReceiver = new InnerReceiver(this, !registered);
791 mReceiver = receiver;
792 mContext = context;
793 mActivityThread = activityThread;
794 mInstrumentation = instrumentation;
795 mRegistered = registered;
796 mLocation = new IntentReceiverLeaked(null);
797 mLocation.fillInStackTrace();
798 }
799
800 void validate(Context context, Handler activityThread) {
801 if (mContext != context) {
802 throw new IllegalStateException(
803 "Receiver " + mReceiver +
804 " registered with differing Context (was " +
805 mContext + " now " + context + ")");
806 }
807 if (mActivityThread != activityThread) {
808 throw new IllegalStateException(
809 "Receiver " + mReceiver +
810 " registered with differing handler (was " +
811 mActivityThread + " now " + activityThread + ")");
812 }
813 }
814
815 IntentReceiverLeaked getLocation() {
816 return mLocation;
817 }
818
819 BroadcastReceiver getIntentReceiver() {
820 return mReceiver;
821 }
Bob Leee5408332009-09-04 18:31:17 -0700822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 IIntentReceiver getIIntentReceiver() {
824 return mIIntentReceiver;
825 }
826
827 void setUnregisterLocation(RuntimeException ex) {
828 mUnregisterLocation = ex;
829 }
830
831 RuntimeException getUnregisterLocation() {
832 return mUnregisterLocation;
833 }
834
835 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700836 String data, Bundle extras, boolean ordered, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 if (DEBUG_BROADCAST) {
838 int seq = intent.getIntExtra("seq", -1);
839 Log.i(TAG, "Enqueueing broadcast " + intent.getAction() + " seq=" + seq
840 + " to " + mReceiver);
841 }
842 Args args = new Args();
843 args.mCurIntent = intent;
844 args.mCurCode = resultCode;
845 args.mCurData = data;
846 args.mCurMap = extras;
847 args.mCurOrdered = ordered;
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700848 args.mCurSticky = sticky;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 if (!mActivityThread.post(args)) {
850 if (mRegistered) {
851 IActivityManager mgr = ActivityManagerNative.getDefault();
852 try {
853 mgr.finishReceiver(mIIntentReceiver, args.mCurCode,
854 args.mCurData, args.mCurMap, false);
855 } catch (RemoteException ex) {
856 }
857 }
858 }
859 }
860
861 }
862
863 public final IServiceConnection getServiceDispatcher(ServiceConnection c,
864 Context context, Handler handler, int flags) {
865 synchronized (mServices) {
866 ServiceDispatcher sd = null;
867 HashMap<ServiceConnection, ServiceDispatcher> map = mServices.get(context);
868 if (map != null) {
869 sd = map.get(c);
870 }
871 if (sd == null) {
872 sd = new ServiceDispatcher(c, context, handler, flags);
873 if (map == null) {
874 map = new HashMap<ServiceConnection, ServiceDispatcher>();
875 mServices.put(context, map);
876 }
877 map.put(c, sd);
878 } else {
879 sd.validate(context, handler);
880 }
881 return sd.getIServiceConnection();
882 }
883 }
884
885 public final IServiceConnection forgetServiceDispatcher(Context context,
886 ServiceConnection c) {
887 synchronized (mServices) {
888 HashMap<ServiceConnection, ServiceDispatcher> map
889 = mServices.get(context);
890 ServiceDispatcher sd = null;
891 if (map != null) {
892 sd = map.get(c);
893 if (sd != null) {
894 map.remove(c);
895 sd.doForget();
896 if (map.size() == 0) {
897 mServices.remove(context);
898 }
899 if ((sd.getFlags()&Context.BIND_DEBUG_UNBIND) != 0) {
900 HashMap<ServiceConnection, ServiceDispatcher> holder
901 = mUnboundServices.get(context);
902 if (holder == null) {
903 holder = new HashMap<ServiceConnection, ServiceDispatcher>();
904 mUnboundServices.put(context, holder);
905 }
906 RuntimeException ex = new IllegalArgumentException(
907 "Originally unbound here:");
908 ex.fillInStackTrace();
909 sd.setUnbindLocation(ex);
910 holder.put(c, sd);
911 }
912 return sd.getIServiceConnection();
913 }
914 }
915 HashMap<ServiceConnection, ServiceDispatcher> holder
916 = mUnboundServices.get(context);
917 if (holder != null) {
918 sd = holder.get(c);
919 if (sd != null) {
920 RuntimeException ex = sd.getUnbindLocation();
921 throw new IllegalArgumentException(
922 "Unbinding Service " + c
923 + " that was already unbound", ex);
924 }
925 }
926 if (context == null) {
927 throw new IllegalStateException("Unbinding Service " + c
928 + " from Context that is no longer in use: " + context);
929 } else {
930 throw new IllegalArgumentException("Service not registered: " + c);
931 }
932 }
933 }
934
935 static final class ServiceDispatcher {
936 private final InnerConnection mIServiceConnection;
937 private final ServiceConnection mConnection;
938 private final Context mContext;
939 private final Handler mActivityThread;
940 private final ServiceConnectionLeaked mLocation;
941 private final int mFlags;
942
943 private RuntimeException mUnbindLocation;
944
945 private boolean mDied;
946
947 private static class ConnectionInfo {
948 IBinder binder;
949 IBinder.DeathRecipient deathMonitor;
950 }
951
952 private static class InnerConnection extends IServiceConnection.Stub {
953 final WeakReference<ServiceDispatcher> mDispatcher;
Bob Leee5408332009-09-04 18:31:17 -0700954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 InnerConnection(ServiceDispatcher sd) {
956 mDispatcher = new WeakReference<ServiceDispatcher>(sd);
957 }
958
959 public void connected(ComponentName name, IBinder service) throws RemoteException {
960 ServiceDispatcher sd = mDispatcher.get();
961 if (sd != null) {
962 sd.connected(name, service);
963 }
964 }
965 }
Bob Leee5408332009-09-04 18:31:17 -0700966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 private final HashMap<ComponentName, ConnectionInfo> mActiveConnections
968 = new HashMap<ComponentName, ConnectionInfo>();
969
970 ServiceDispatcher(ServiceConnection conn,
971 Context context, Handler activityThread, int flags) {
972 mIServiceConnection = new InnerConnection(this);
973 mConnection = conn;
974 mContext = context;
975 mActivityThread = activityThread;
976 mLocation = new ServiceConnectionLeaked(null);
977 mLocation.fillInStackTrace();
978 mFlags = flags;
979 }
980
981 void validate(Context context, Handler activityThread) {
982 if (mContext != context) {
983 throw new RuntimeException(
984 "ServiceConnection " + mConnection +
985 " registered with differing Context (was " +
986 mContext + " now " + context + ")");
987 }
988 if (mActivityThread != activityThread) {
989 throw new RuntimeException(
990 "ServiceConnection " + mConnection +
991 " registered with differing handler (was " +
992 mActivityThread + " now " + activityThread + ")");
993 }
994 }
995
996 void doForget() {
997 synchronized(this) {
998 Iterator<ConnectionInfo> it = mActiveConnections.values().iterator();
999 while (it.hasNext()) {
1000 ConnectionInfo ci = it.next();
1001 ci.binder.unlinkToDeath(ci.deathMonitor, 0);
1002 }
1003 mActiveConnections.clear();
1004 }
1005 }
1006
1007 ServiceConnectionLeaked getLocation() {
1008 return mLocation;
1009 }
1010
1011 ServiceConnection getServiceConnection() {
1012 return mConnection;
1013 }
1014
1015 IServiceConnection getIServiceConnection() {
1016 return mIServiceConnection;
1017 }
Bob Leee5408332009-09-04 18:31:17 -07001018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 int getFlags() {
1020 return mFlags;
1021 }
1022
1023 void setUnbindLocation(RuntimeException ex) {
1024 mUnbindLocation = ex;
1025 }
1026
1027 RuntimeException getUnbindLocation() {
1028 return mUnbindLocation;
1029 }
1030
1031 public void connected(ComponentName name, IBinder service) {
1032 if (mActivityThread != null) {
1033 mActivityThread.post(new RunConnection(name, service, 0));
1034 } else {
1035 doConnected(name, service);
1036 }
1037 }
1038
1039 public void death(ComponentName name, IBinder service) {
1040 ConnectionInfo old;
1041
1042 synchronized (this) {
1043 mDied = true;
1044 old = mActiveConnections.remove(name);
1045 if (old == null || old.binder != service) {
1046 // Death for someone different than who we last
1047 // reported... just ignore it.
1048 return;
1049 }
1050 old.binder.unlinkToDeath(old.deathMonitor, 0);
1051 }
1052
1053 if (mActivityThread != null) {
1054 mActivityThread.post(new RunConnection(name, service, 1));
1055 } else {
1056 doDeath(name, service);
1057 }
1058 }
1059
1060 public void doConnected(ComponentName name, IBinder service) {
1061 ConnectionInfo old;
1062 ConnectionInfo info;
1063
1064 synchronized (this) {
1065 old = mActiveConnections.get(name);
1066 if (old != null && old.binder == service) {
1067 // Huh, already have this one. Oh well!
1068 return;
1069 }
1070
1071 if (service != null) {
1072 // A new service is being connected... set it all up.
1073 mDied = false;
1074 info = new ConnectionInfo();
1075 info.binder = service;
1076 info.deathMonitor = new DeathMonitor(name, service);
1077 try {
1078 service.linkToDeath(info.deathMonitor, 0);
1079 mActiveConnections.put(name, info);
1080 } catch (RemoteException e) {
1081 // This service was dead before we got it... just
1082 // don't do anything with it.
1083 mActiveConnections.remove(name);
1084 return;
1085 }
1086
1087 } else {
1088 // The named service is being disconnected... clean up.
1089 mActiveConnections.remove(name);
1090 }
1091
1092 if (old != null) {
1093 old.binder.unlinkToDeath(old.deathMonitor, 0);
1094 }
1095 }
1096
1097 // If there was an old service, it is not disconnected.
1098 if (old != null) {
1099 mConnection.onServiceDisconnected(name);
1100 }
1101 // If there is a new service, it is now connected.
1102 if (service != null) {
1103 mConnection.onServiceConnected(name, service);
1104 }
1105 }
1106
1107 public void doDeath(ComponentName name, IBinder service) {
1108 mConnection.onServiceDisconnected(name);
1109 }
1110
1111 private final class RunConnection implements Runnable {
1112 RunConnection(ComponentName name, IBinder service, int command) {
1113 mName = name;
1114 mService = service;
1115 mCommand = command;
1116 }
1117
1118 public void run() {
1119 if (mCommand == 0) {
1120 doConnected(mName, mService);
1121 } else if (mCommand == 1) {
1122 doDeath(mName, mService);
1123 }
1124 }
1125
1126 final ComponentName mName;
1127 final IBinder mService;
1128 final int mCommand;
1129 }
1130
1131 private final class DeathMonitor implements IBinder.DeathRecipient
1132 {
1133 DeathMonitor(ComponentName name, IBinder service) {
1134 mName = name;
1135 mService = service;
1136 }
1137
1138 public void binderDied() {
1139 death(mName, mService);
1140 }
1141
1142 final ComponentName mName;
1143 final IBinder mService;
1144 }
1145 }
1146 }
1147
1148 private static ApplicationContext mSystemContext = null;
1149
1150 private static final class ActivityRecord {
1151 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001152 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 Intent intent;
1154 Bundle state;
1155 Activity activity;
1156 Window window;
1157 Activity parent;
1158 String embeddedID;
1159 Object lastNonConfigurationInstance;
1160 HashMap<String,Object> lastNonConfigurationChildInstances;
1161 boolean paused;
1162 boolean stopped;
1163 boolean hideForNow;
1164 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -07001165 Configuration createdConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 ActivityRecord nextIdle;
1167
1168 ActivityInfo activityInfo;
1169 PackageInfo packageInfo;
1170
1171 List<ResultInfo> pendingResults;
1172 List<Intent> pendingIntents;
1173
1174 boolean startsNotResumed;
1175 boolean isForward;
1176
1177 ActivityRecord() {
1178 parent = null;
1179 embeddedID = null;
1180 paused = false;
1181 stopped = false;
1182 hideForNow = false;
1183 nextIdle = null;
1184 }
1185
1186 public String toString() {
1187 ComponentName componentName = intent.getComponent();
1188 return "ActivityRecord{"
1189 + Integer.toHexString(System.identityHashCode(this))
1190 + " token=" + token + " " + (componentName == null
1191 ? "no component name" : componentName.toShortString())
1192 + "}";
1193 }
1194 }
1195
1196 private final class ProviderRecord implements IBinder.DeathRecipient {
1197 final String mName;
1198 final IContentProvider mProvider;
1199 final ContentProvider mLocalProvider;
1200
1201 ProviderRecord(String name, IContentProvider provider,
1202 ContentProvider localProvider) {
1203 mName = name;
1204 mProvider = provider;
1205 mLocalProvider = localProvider;
1206 }
1207
1208 public void binderDied() {
1209 removeDeadProvider(mName, mProvider);
1210 }
1211 }
1212
1213 private static final class NewIntentData {
1214 List<Intent> intents;
1215 IBinder token;
1216 public String toString() {
1217 return "NewIntentData{intents=" + intents + " token=" + token + "}";
1218 }
1219 }
1220
1221 private static final class ReceiverData {
1222 Intent intent;
1223 ActivityInfo info;
1224 int resultCode;
1225 String resultData;
1226 Bundle resultExtras;
1227 boolean sync;
1228 boolean resultAbort;
1229 public String toString() {
1230 return "ReceiverData{intent=" + intent + " packageName=" +
1231 info.packageName + " resultCode=" + resultCode
1232 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
1233 }
1234 }
1235
Christopher Tate181fafa2009-05-14 11:12:14 -07001236 private static final class CreateBackupAgentData {
1237 ApplicationInfo appInfo;
1238 int backupMode;
1239 public String toString() {
1240 return "CreateBackupAgentData{appInfo=" + appInfo
1241 + " backupAgent=" + appInfo.backupAgentName
1242 + " mode=" + backupMode + "}";
1243 }
1244 }
Bob Leee5408332009-09-04 18:31:17 -07001245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 private static final class CreateServiceData {
1247 IBinder token;
1248 ServiceInfo info;
1249 Intent intent;
1250 public String toString() {
1251 return "CreateServiceData{token=" + token + " className="
1252 + info.name + " packageName=" + info.packageName
1253 + " intent=" + intent + "}";
1254 }
1255 }
1256
1257 private static final class BindServiceData {
1258 IBinder token;
1259 Intent intent;
1260 boolean rebind;
1261 public String toString() {
1262 return "BindServiceData{token=" + token + " intent=" + intent + "}";
1263 }
1264 }
1265
1266 private static final class ServiceArgsData {
1267 IBinder token;
1268 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001269 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 Intent args;
1271 public String toString() {
1272 return "ServiceArgsData{token=" + token + " startId=" + startId
1273 + " args=" + args + "}";
1274 }
1275 }
1276
1277 private static final class AppBindData {
1278 PackageInfo info;
1279 String processName;
1280 ApplicationInfo appInfo;
1281 List<ProviderInfo> providers;
1282 ComponentName instrumentationName;
1283 String profileFile;
1284 Bundle instrumentationArgs;
1285 IInstrumentationWatcher instrumentationWatcher;
1286 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001287 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 Configuration config;
1289 boolean handlingProfiling;
1290 public String toString() {
1291 return "AppBindData{appInfo=" + appInfo + "}";
1292 }
1293 }
1294
1295 private static final class DumpServiceInfo {
1296 FileDescriptor fd;
1297 IBinder service;
1298 String[] args;
1299 boolean dumped;
1300 }
1301
1302 private static final class ResultData {
1303 IBinder token;
1304 List<ResultInfo> results;
1305 public String toString() {
1306 return "ResultData{token=" + token + " results" + results + "}";
1307 }
1308 }
1309
1310 private static final class ContextCleanupInfo {
1311 ApplicationContext context;
1312 String what;
1313 String who;
1314 }
1315
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001316 private static final class ProfilerControlData {
1317 String path;
1318 ParcelFileDescriptor fd;
1319 }
1320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 private final class ApplicationThread extends ApplicationThreadNative {
1322 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
1323 private static final String ONE_COUNT_COLUMN = "%17s %8d";
1324 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Bob Leee5408332009-09-04 18:31:17 -07001325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 // Formatting for checkin service - update version if row format changes
1327 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -07001328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 public final void schedulePauseActivity(IBinder token, boolean finished,
1330 boolean userLeaving, int configChanges) {
1331 queueOrSendMessage(
1332 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
1333 token,
1334 (userLeaving ? 1 : 0),
1335 configChanges);
1336 }
1337
1338 public final void scheduleStopActivity(IBinder token, boolean showWindow,
1339 int configChanges) {
1340 queueOrSendMessage(
1341 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
1342 token, 0, configChanges);
1343 }
1344
1345 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
1346 queueOrSendMessage(
1347 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
1348 token);
1349 }
1350
1351 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
1352 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
1353 }
1354
1355 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
1356 ResultData res = new ResultData();
1357 res.token = token;
1358 res.results = results;
1359 queueOrSendMessage(H.SEND_RESULT, res);
1360 }
1361
1362 // we use token to identify this activity without having to send the
1363 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001364 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
1366 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
1367 ActivityRecord r = new ActivityRecord();
1368
1369 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001370 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 r.intent = intent;
1372 r.activityInfo = info;
1373 r.state = state;
1374
1375 r.pendingResults = pendingResults;
1376 r.pendingIntents = pendingNewIntents;
1377
1378 r.startsNotResumed = notResumed;
1379 r.isForward = isForward;
1380
1381 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
1382 }
1383
1384 public final void scheduleRelaunchActivity(IBinder token,
1385 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001386 int configChanges, boolean notResumed, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 ActivityRecord r = new ActivityRecord();
1388
1389 r.token = token;
1390 r.pendingResults = pendingResults;
1391 r.pendingIntents = pendingNewIntents;
1392 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001393 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394
1395 synchronized (mRelaunchingActivities) {
1396 mRelaunchingActivities.add(r);
1397 }
Bob Leee5408332009-09-04 18:31:17 -07001398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
1400 }
1401
1402 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
1403 NewIntentData data = new NewIntentData();
1404 data.intents = intents;
1405 data.token = token;
1406
1407 queueOrSendMessage(H.NEW_INTENT, data);
1408 }
1409
1410 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
1411 int configChanges) {
1412 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
1413 configChanges);
1414 }
1415
1416 public final void scheduleReceiver(Intent intent, ActivityInfo info,
1417 int resultCode, String data, Bundle extras, boolean sync) {
1418 ReceiverData r = new ReceiverData();
1419
1420 r.intent = intent;
1421 r.info = info;
1422 r.resultCode = resultCode;
1423 r.resultData = data;
1424 r.resultExtras = extras;
1425 r.sync = sync;
1426
1427 queueOrSendMessage(H.RECEIVER, r);
1428 }
1429
Christopher Tate181fafa2009-05-14 11:12:14 -07001430 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
1431 CreateBackupAgentData d = new CreateBackupAgentData();
1432 d.appInfo = app;
1433 d.backupMode = backupMode;
1434
1435 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
1436 }
1437
1438 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
1439 CreateBackupAgentData d = new CreateBackupAgentData();
1440 d.appInfo = app;
1441
1442 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
1443 }
1444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 public final void scheduleCreateService(IBinder token,
1446 ServiceInfo info) {
1447 CreateServiceData s = new CreateServiceData();
1448 s.token = token;
1449 s.info = info;
1450
1451 queueOrSendMessage(H.CREATE_SERVICE, s);
1452 }
1453
1454 public final void scheduleBindService(IBinder token, Intent intent,
1455 boolean rebind) {
1456 BindServiceData s = new BindServiceData();
1457 s.token = token;
1458 s.intent = intent;
1459 s.rebind = rebind;
1460
1461 queueOrSendMessage(H.BIND_SERVICE, s);
1462 }
1463
1464 public final void scheduleUnbindService(IBinder token, Intent intent) {
1465 BindServiceData s = new BindServiceData();
1466 s.token = token;
1467 s.intent = intent;
1468
1469 queueOrSendMessage(H.UNBIND_SERVICE, s);
1470 }
1471
1472 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001473 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 ServiceArgsData s = new ServiceArgsData();
1475 s.token = token;
1476 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001477 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 s.args = args;
1479
1480 queueOrSendMessage(H.SERVICE_ARGS, s);
1481 }
1482
1483 public final void scheduleStopService(IBinder token) {
1484 queueOrSendMessage(H.STOP_SERVICE, token);
1485 }
1486
1487 public final void bindApplication(String processName,
1488 ApplicationInfo appInfo, List<ProviderInfo> providers,
1489 ComponentName instrumentationName, String profileFile,
1490 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -07001491 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493
1494 if (services != null) {
1495 // Setup the service cache in the ServiceManager
1496 ServiceManager.initServiceCache(services);
1497 }
1498
1499 AppBindData data = new AppBindData();
1500 data.processName = processName;
1501 data.appInfo = appInfo;
1502 data.providers = providers;
1503 data.instrumentationName = instrumentationName;
1504 data.profileFile = profileFile;
1505 data.instrumentationArgs = instrumentationArgs;
1506 data.instrumentationWatcher = instrumentationWatcher;
1507 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001508 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 data.config = config;
1510 queueOrSendMessage(H.BIND_APPLICATION, data);
1511 }
1512
1513 public final void scheduleExit() {
1514 queueOrSendMessage(H.EXIT_APPLICATION, null);
1515 }
1516
Christopher Tate5e1ab332009-09-01 20:32:49 -07001517 public final void scheduleSuicide() {
1518 queueOrSendMessage(H.SUICIDE, null);
1519 }
1520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 public void requestThumbnail(IBinder token) {
1522 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
1523 }
1524
1525 public void scheduleConfigurationChanged(Configuration config) {
1526 synchronized (mRelaunchingActivities) {
1527 mPendingConfiguration = config;
1528 }
1529 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
1530 }
1531
1532 public void updateTimeZone() {
1533 TimeZone.setDefault(null);
1534 }
1535
1536 public void processInBackground() {
1537 mH.removeMessages(H.GC_WHEN_IDLE);
1538 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1539 }
1540
1541 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
1542 DumpServiceInfo data = new DumpServiceInfo();
1543 data.fd = fd;
1544 data.service = servicetoken;
1545 data.args = args;
1546 data.dumped = false;
1547 queueOrSendMessage(H.DUMP_SERVICE, data);
1548 synchronized (data) {
1549 while (!data.dumped) {
1550 try {
1551 data.wait();
1552 } catch (InterruptedException e) {
1553 // no need to do anything here, we will keep waiting until
1554 // dumped is set
1555 }
1556 }
1557 }
1558 }
1559
1560 // This function exists to make sure all receiver dispatching is
1561 // correctly ordered, since these are one-way calls and the binder driver
1562 // applies transaction ordering per object for such calls.
1563 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001564 int resultCode, String dataStr, Bundle extras, boolean ordered,
1565 boolean sticky) throws RemoteException {
1566 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
Bob Leee5408332009-09-04 18:31:17 -07001568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 public void scheduleLowMemory() {
1570 queueOrSendMessage(H.LOW_MEMORY, null);
1571 }
1572
1573 public void scheduleActivityConfigurationChanged(IBinder token) {
1574 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
1575 }
1576
1577 public void requestPss() {
1578 try {
1579 ActivityManagerNative.getDefault().reportPss(this,
1580 (int)Process.getPss(Process.myPid()));
1581 } catch (RemoteException e) {
1582 }
1583 }
Bob Leee5408332009-09-04 18:31:17 -07001584
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001585 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
1586 ProfilerControlData pcd = new ProfilerControlData();
1587 pcd.path = path;
1588 pcd.fd = fd;
1589 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001590 }
1591
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001592 public void setSchedulingGroup(int group) {
1593 // Note: do this immediately, since going into the foreground
1594 // should happen regardless of what pending work we have to do
1595 // and the activity manager will wait for us to report back that
1596 // we are done before sending us to the background.
1597 try {
1598 Process.setProcessGroup(Process.myPid(), group);
1599 } catch (Exception e) {
1600 Log.w(TAG, "Failed setting process group to " + group, e);
1601 }
1602 }
Bob Leee5408332009-09-04 18:31:17 -07001603
Dianne Hackborn3025ef32009-08-31 21:31:47 -07001604 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
1605 Debug.getMemoryInfo(outInfo);
1606 }
Bob Leee5408332009-09-04 18:31:17 -07001607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 @Override
1609 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1610 long nativeMax = Debug.getNativeHeapSize() / 1024;
1611 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1612 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1613
1614 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
1615 Debug.getMemoryInfo(memInfo);
1616
1617 final int nativeShared = memInfo.nativeSharedDirty;
1618 final int dalvikShared = memInfo.dalvikSharedDirty;
1619 final int otherShared = memInfo.otherSharedDirty;
1620
1621 final int nativePrivate = memInfo.nativePrivateDirty;
1622 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
1623 final int otherPrivate = memInfo.otherPrivateDirty;
1624
1625 Runtime runtime = Runtime.getRuntime();
1626
1627 long dalvikMax = runtime.totalMemory() / 1024;
1628 long dalvikFree = runtime.freeMemory() / 1024;
1629 long dalvikAllocated = dalvikMax - dalvikFree;
1630 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1631 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
1632 long appContextInstanceCount = ApplicationContext.getInstanceCount();
1633 long activityInstanceCount = Activity.getInstanceCount();
1634 int globalAssetCount = AssetManager.getGlobalAssetCount();
1635 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1636 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1637 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1638 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1639 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
1640 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
1641 SQLiteDebug.PagerStats stats = new SQLiteDebug.PagerStats();
1642 SQLiteDebug.getPagerStats(stats);
Bob Leee5408332009-09-04 18:31:17 -07001643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 // Check to see if we were called by checkin server. If so, print terse format.
1645 boolean doCheckinFormat = false;
1646 if (args != null) {
1647 for (String arg : args) {
1648 if ("-c".equals(arg)) doCheckinFormat = true;
1649 }
1650 }
Bob Leee5408332009-09-04 18:31:17 -07001651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 // For checkin, we print one long comma-separated list of values
1653 if (doCheckinFormat) {
1654 // NOTE: if you change anything significant below, also consider changing
1655 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -07001656 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -07001658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 // Header
1660 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
1661 pw.print(Process.myPid()); pw.print(',');
1662 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 // Heap info - max
1665 pw.print(nativeMax); pw.print(',');
1666 pw.print(dalvikMax); pw.print(',');
1667 pw.print("N/A,");
1668 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 // Heap info - allocated
1671 pw.print(nativeAllocated); pw.print(',');
1672 pw.print(dalvikAllocated); pw.print(',');
1673 pw.print("N/A,");
1674 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 // Heap info - free
1677 pw.print(nativeFree); pw.print(',');
1678 pw.print(dalvikFree); pw.print(',');
1679 pw.print("N/A,");
1680 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 // Heap info - proportional set size
1683 pw.print(memInfo.nativePss); pw.print(',');
1684 pw.print(memInfo.dalvikPss); pw.print(',');
1685 pw.print(memInfo.otherPss); pw.print(',');
1686 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -07001689 pw.print(nativeShared); pw.print(',');
1690 pw.print(dalvikShared); pw.print(',');
1691 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -07001695 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 pw.print(dalvikPrivate); pw.print(',');
1697 pw.print(otherPrivate); pw.print(',');
1698 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 // Object counts
1701 pw.print(viewInstanceCount); pw.print(',');
1702 pw.print(viewRootInstanceCount); pw.print(',');
1703 pw.print(appContextInstanceCount); pw.print(',');
1704 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 pw.print(globalAssetCount); pw.print(',');
1707 pw.print(globalAssetManagerCount); pw.print(',');
1708 pw.print(binderLocalObjectCount); pw.print(',');
1709 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 pw.print(binderDeathObjectCount); pw.print(',');
1712 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 // SQL
1715 pw.print(sqliteAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001716 pw.print(stats.databaseBytes / 1024); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 pw.print(stats.numPagers); pw.print(',');
1718 pw.print((stats.totalBytes - stats.referencedBytes) / 1024); pw.print(',');
1719 pw.print(stats.referencedBytes / 1024); pw.print('\n');
Bob Leee5408332009-09-04 18:31:17 -07001720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 return;
1722 }
Bob Leee5408332009-09-04 18:31:17 -07001723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 // otherwise, show human-readable format
1725 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
1726 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
1727 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
1728 nativeAllocated + dalvikAllocated);
1729 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
1730 nativeFree + dalvikFree);
1731
1732 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
1733 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
1734
1735 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
1736 nativeShared + dalvikShared + otherShared);
1737 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
1738 nativePrivate + dalvikPrivate + otherPrivate);
1739
1740 pw.println(" ");
1741 pw.println(" Objects");
1742 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
1743 viewRootInstanceCount);
1744
1745 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1746 "Activities:", activityInstanceCount);
1747
1748 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1749 "AssetManagers:", globalAssetManagerCount);
1750
1751 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1752 "Proxy Binders:", binderProxyObjectCount);
1753 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1754
1755 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 // SQLite mem info
1758 pw.println(" ");
1759 pw.println(" SQL");
1760 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "dbFiles:",
1761 stats.databaseBytes / 1024);
1762 printRow(pw, TWO_COUNT_COLUMNS, "numPagers:", stats.numPagers, "inactivePageKB:",
1763 (stats.totalBytes - stats.referencedBytes) / 1024);
1764 printRow(pw, ONE_COUNT_COLUMN, "activePageKB:", stats.referencedBytes / 1024);
Bob Leee5408332009-09-04 18:31:17 -07001765
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001766 // Asset details.
1767 String assetAlloc = AssetManager.getAssetAllocations();
1768 if (assetAlloc != null) {
1769 pw.println(" ");
1770 pw.println(" Asset Allocations");
1771 pw.print(assetAlloc);
1772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774
1775 private void printRow(PrintWriter pw, String format, Object...objs) {
1776 pw.println(String.format(format, objs));
1777 }
1778 }
1779
1780 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -07001781 private H() {
1782 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
1783 }
1784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 public static final int LAUNCH_ACTIVITY = 100;
1786 public static final int PAUSE_ACTIVITY = 101;
1787 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1788 public static final int STOP_ACTIVITY_SHOW = 103;
1789 public static final int STOP_ACTIVITY_HIDE = 104;
1790 public static final int SHOW_WINDOW = 105;
1791 public static final int HIDE_WINDOW = 106;
1792 public static final int RESUME_ACTIVITY = 107;
1793 public static final int SEND_RESULT = 108;
1794 public static final int DESTROY_ACTIVITY = 109;
1795 public static final int BIND_APPLICATION = 110;
1796 public static final int EXIT_APPLICATION = 111;
1797 public static final int NEW_INTENT = 112;
1798 public static final int RECEIVER = 113;
1799 public static final int CREATE_SERVICE = 114;
1800 public static final int SERVICE_ARGS = 115;
1801 public static final int STOP_SERVICE = 116;
1802 public static final int REQUEST_THUMBNAIL = 117;
1803 public static final int CONFIGURATION_CHANGED = 118;
1804 public static final int CLEAN_UP_CONTEXT = 119;
1805 public static final int GC_WHEN_IDLE = 120;
1806 public static final int BIND_SERVICE = 121;
1807 public static final int UNBIND_SERVICE = 122;
1808 public static final int DUMP_SERVICE = 123;
1809 public static final int LOW_MEMORY = 124;
1810 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1811 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001812 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001813 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001814 public static final int DESTROY_BACKUP_AGENT = 129;
1815 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001816 public static final int REMOVE_PROVIDER = 131;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 String codeToString(int code) {
1818 if (localLOGV) {
1819 switch (code) {
1820 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1821 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1822 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1823 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1824 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1825 case SHOW_WINDOW: return "SHOW_WINDOW";
1826 case HIDE_WINDOW: return "HIDE_WINDOW";
1827 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1828 case SEND_RESULT: return "SEND_RESULT";
1829 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1830 case BIND_APPLICATION: return "BIND_APPLICATION";
1831 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1832 case NEW_INTENT: return "NEW_INTENT";
1833 case RECEIVER: return "RECEIVER";
1834 case CREATE_SERVICE: return "CREATE_SERVICE";
1835 case SERVICE_ARGS: return "SERVICE_ARGS";
1836 case STOP_SERVICE: return "STOP_SERVICE";
1837 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1838 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1839 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1840 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1841 case BIND_SERVICE: return "BIND_SERVICE";
1842 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1843 case DUMP_SERVICE: return "DUMP_SERVICE";
1844 case LOW_MEMORY: return "LOW_MEMORY";
1845 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1846 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001847 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001848 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1849 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001850 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001851 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
1853 }
1854 return "(unknown)";
1855 }
1856 public void handleMessage(Message msg) {
1857 switch (msg.what) {
1858 case LAUNCH_ACTIVITY: {
1859 ActivityRecord r = (ActivityRecord)msg.obj;
1860
1861 r.packageInfo = getPackageInfoNoCheck(
1862 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001863 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 } break;
1865 case RELAUNCH_ACTIVITY: {
1866 ActivityRecord r = (ActivityRecord)msg.obj;
1867 handleRelaunchActivity(r, msg.arg1);
1868 } break;
1869 case PAUSE_ACTIVITY:
1870 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001871 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 break;
1873 case PAUSE_ACTIVITY_FINISHING:
1874 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1875 break;
1876 case STOP_ACTIVITY_SHOW:
1877 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1878 break;
1879 case STOP_ACTIVITY_HIDE:
1880 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1881 break;
1882 case SHOW_WINDOW:
1883 handleWindowVisibility((IBinder)msg.obj, true);
1884 break;
1885 case HIDE_WINDOW:
1886 handleWindowVisibility((IBinder)msg.obj, false);
1887 break;
1888 case RESUME_ACTIVITY:
1889 handleResumeActivity((IBinder)msg.obj, true,
1890 msg.arg1 != 0);
1891 break;
1892 case SEND_RESULT:
1893 handleSendResult((ResultData)msg.obj);
1894 break;
1895 case DESTROY_ACTIVITY:
1896 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1897 msg.arg2, false);
1898 break;
1899 case BIND_APPLICATION:
1900 AppBindData data = (AppBindData)msg.obj;
1901 handleBindApplication(data);
1902 break;
1903 case EXIT_APPLICATION:
1904 if (mInitialApplication != null) {
1905 mInitialApplication.onTerminate();
1906 }
1907 Looper.myLooper().quit();
1908 break;
1909 case NEW_INTENT:
1910 handleNewIntent((NewIntentData)msg.obj);
1911 break;
1912 case RECEIVER:
1913 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001914 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 break;
1916 case CREATE_SERVICE:
1917 handleCreateService((CreateServiceData)msg.obj);
1918 break;
1919 case BIND_SERVICE:
1920 handleBindService((BindServiceData)msg.obj);
1921 break;
1922 case UNBIND_SERVICE:
1923 handleUnbindService((BindServiceData)msg.obj);
1924 break;
1925 case SERVICE_ARGS:
1926 handleServiceArgs((ServiceArgsData)msg.obj);
1927 break;
1928 case STOP_SERVICE:
1929 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001930 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 break;
1932 case REQUEST_THUMBNAIL:
1933 handleRequestThumbnail((IBinder)msg.obj);
1934 break;
1935 case CONFIGURATION_CHANGED:
1936 handleConfigurationChanged((Configuration)msg.obj);
1937 break;
1938 case CLEAN_UP_CONTEXT:
1939 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1940 cci.context.performFinalCleanup(cci.who, cci.what);
1941 break;
1942 case GC_WHEN_IDLE:
1943 scheduleGcIdler();
1944 break;
1945 case DUMP_SERVICE:
1946 handleDumpService((DumpServiceInfo)msg.obj);
1947 break;
1948 case LOW_MEMORY:
1949 handleLowMemory();
1950 break;
1951 case ACTIVITY_CONFIGURATION_CHANGED:
1952 handleActivityConfigurationChanged((IBinder)msg.obj);
1953 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001954 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001955 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001956 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001957 case CREATE_BACKUP_AGENT:
1958 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1959 break;
1960 case DESTROY_BACKUP_AGENT:
1961 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1962 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001963 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001964 Process.killProcess(Process.myPid());
1965 break;
1966 case REMOVE_PROVIDER:
1967 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001968 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 }
1970 }
Bob Leee5408332009-09-04 18:31:17 -07001971
1972 void maybeSnapshot() {
1973 if (mBoundApplication != null) {
1974 SamplingProfilerIntegration.writeSnapshot(
1975 mBoundApplication.processName);
1976 }
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979
1980 private final class Idler implements MessageQueue.IdleHandler {
1981 public final boolean queueIdle() {
1982 ActivityRecord a = mNewActivities;
1983 if (a != null) {
1984 mNewActivities = null;
1985 IActivityManager am = ActivityManagerNative.getDefault();
1986 ActivityRecord prev;
1987 do {
1988 if (localLOGV) Log.v(
1989 TAG, "Reporting idle of " + a +
1990 " finished=" +
1991 (a.activity != null ? a.activity.mFinished : false));
1992 if (a.activity != null && !a.activity.mFinished) {
1993 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001994 am.activityIdle(a.token, a.createdConfig);
1995 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 } catch (RemoteException ex) {
1997 }
1998 }
1999 prev = a;
2000 a = a.nextIdle;
2001 prev.nextIdle = null;
2002 } while (a != null);
2003 }
2004 return false;
2005 }
2006 }
2007
2008 final class GcIdler implements MessageQueue.IdleHandler {
2009 public final boolean queueIdle() {
2010 doGcIfNeeded();
2011 return false;
2012 }
2013 }
2014
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002015 private final static class ResourcesKey {
2016 final private String mResDir;
2017 final private float mScale;
2018 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07002019
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002020 ResourcesKey(String resDir, float scale) {
2021 mResDir = resDir;
2022 mScale = scale;
2023 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
2024 }
Bob Leee5408332009-09-04 18:31:17 -07002025
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002026 @Override
2027 public int hashCode() {
2028 return mHash;
2029 }
2030
2031 @Override
2032 public boolean equals(Object obj) {
2033 if (!(obj instanceof ResourcesKey)) {
2034 return false;
2035 }
2036 ResourcesKey peer = (ResourcesKey) obj;
2037 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
2038 }
2039 }
2040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 static IPackageManager sPackageManager;
2042
2043 final ApplicationThread mAppThread = new ApplicationThread();
2044 final Looper mLooper = Looper.myLooper();
2045 final H mH = new H();
2046 final HashMap<IBinder, ActivityRecord> mActivities
2047 = new HashMap<IBinder, ActivityRecord>();
2048 // List of new activities (via ActivityRecord.nextIdle) that should
2049 // be reported when next we idle.
2050 ActivityRecord mNewActivities = null;
2051 // Number of activities that are currently visible on-screen.
2052 int mNumVisibleActivities = 0;
2053 final HashMap<IBinder, Service> mServices
2054 = new HashMap<IBinder, Service>();
2055 AppBindData mBoundApplication;
2056 Configuration mConfiguration;
2057 Application mInitialApplication;
2058 final ArrayList<Application> mAllApplications
2059 = new ArrayList<Application>();
Christopher Tate181fafa2009-05-14 11:12:14 -07002060 // set of instantiated backup agents, keyed by package name
2061 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 static final ThreadLocal sThreadLocal = new ThreadLocal();
2063 Instrumentation mInstrumentation;
2064 String mInstrumentationAppDir = null;
2065 String mInstrumentationAppPackage = null;
2066 String mInstrumentedAppDir = null;
2067 boolean mSystemThread = false;
2068
2069 /**
2070 * Activities that are enqueued to be relaunched. This list is accessed
2071 * by multiple threads, so you must synchronize on it when accessing it.
2072 */
2073 final ArrayList<ActivityRecord> mRelaunchingActivities
2074 = new ArrayList<ActivityRecord>();
2075 Configuration mPendingConfiguration = null;
Bob Leee5408332009-09-04 18:31:17 -07002076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 // These can be accessed by multiple threads; mPackages is the lock.
2078 // XXX For now we keep around information about all packages we have
2079 // seen, not removing entries from this map.
2080 final HashMap<String, WeakReference<PackageInfo>> mPackages
2081 = new HashMap<String, WeakReference<PackageInfo>>();
2082 final HashMap<String, WeakReference<PackageInfo>> mResourcePackages
2083 = new HashMap<String, WeakReference<PackageInfo>>();
2084 Display mDisplay = null;
2085 DisplayMetrics mDisplayMetrics = null;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002086 HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
2087 = new HashMap<ResourcesKey, WeakReference<Resources> >();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088
2089 // The lock of mProviderMap protects the following variables.
2090 final HashMap<String, ProviderRecord> mProviderMap
2091 = new HashMap<String, ProviderRecord>();
2092 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
2093 = new HashMap<IBinder, ProviderRefCount>();
2094 final HashMap<IBinder, ProviderRecord> mLocalProviders
2095 = new HashMap<IBinder, ProviderRecord>();
2096
2097 final GcIdler mGcIdler = new GcIdler();
2098 boolean mGcIdlerScheduled = false;
2099
2100 public final PackageInfo getPackageInfo(String packageName, int flags) {
2101 synchronized (mPackages) {
2102 WeakReference<PackageInfo> ref;
2103 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
2104 ref = mPackages.get(packageName);
2105 } else {
2106 ref = mResourcePackages.get(packageName);
2107 }
2108 PackageInfo packageInfo = ref != null ? ref.get() : null;
2109 //Log.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
2110 if (packageInfo != null && (packageInfo.mResources == null
2111 || packageInfo.mResources.getAssets().isUpToDate())) {
2112 if (packageInfo.isSecurityViolation()
2113 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2114 throw new SecurityException(
2115 "Requesting code from " + packageName
2116 + " to be run in process "
2117 + mBoundApplication.processName
2118 + "/" + mBoundApplication.appInfo.uid);
2119 }
2120 return packageInfo;
2121 }
2122 }
2123
2124 ApplicationInfo ai = null;
2125 try {
2126 ai = getPackageManager().getApplicationInfo(packageName,
2127 PackageManager.GET_SHARED_LIBRARY_FILES);
2128 } catch (RemoteException e) {
2129 }
2130
2131 if (ai != null) {
2132 return getPackageInfo(ai, flags);
2133 }
2134
2135 return null;
2136 }
2137
2138 public final PackageInfo getPackageInfo(ApplicationInfo ai, int flags) {
2139 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2140 boolean securityViolation = includeCode && ai.uid != 0
2141 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
2142 ? ai.uid != mBoundApplication.appInfo.uid : true);
2143 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2144 |Context.CONTEXT_IGNORE_SECURITY))
2145 == Context.CONTEXT_INCLUDE_CODE) {
2146 if (securityViolation) {
2147 String msg = "Requesting code from " + ai.packageName
2148 + " (with uid " + ai.uid + ")";
2149 if (mBoundApplication != null) {
2150 msg = msg + " to be run in process "
2151 + mBoundApplication.processName + " (with uid "
2152 + mBoundApplication.appInfo.uid + ")";
2153 }
2154 throw new SecurityException(msg);
2155 }
2156 }
2157 return getPackageInfo(ai, null, securityViolation, includeCode);
2158 }
2159
2160 public final PackageInfo getPackageInfoNoCheck(ApplicationInfo ai) {
2161 return getPackageInfo(ai, null, false, true);
2162 }
2163
2164 private final PackageInfo getPackageInfo(ApplicationInfo aInfo,
2165 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
2166 synchronized (mPackages) {
2167 WeakReference<PackageInfo> ref;
2168 if (includeCode) {
2169 ref = mPackages.get(aInfo.packageName);
2170 } else {
2171 ref = mResourcePackages.get(aInfo.packageName);
2172 }
2173 PackageInfo packageInfo = ref != null ? ref.get() : null;
2174 if (packageInfo == null || (packageInfo.mResources != null
2175 && !packageInfo.mResources.getAssets().isUpToDate())) {
2176 if (localLOGV) Log.v(TAG, (includeCode ? "Loading code package "
2177 : "Loading resource-only package ") + aInfo.packageName
2178 + " (in " + (mBoundApplication != null
2179 ? mBoundApplication.processName : null)
2180 + ")");
2181 packageInfo =
2182 new PackageInfo(this, aInfo, this, baseLoader,
2183 securityViolation, includeCode &&
2184 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
2185 if (includeCode) {
2186 mPackages.put(aInfo.packageName,
2187 new WeakReference<PackageInfo>(packageInfo));
2188 } else {
2189 mResourcePackages.put(aInfo.packageName,
2190 new WeakReference<PackageInfo>(packageInfo));
2191 }
2192 }
2193 return packageInfo;
2194 }
2195 }
2196
2197 public final boolean hasPackageInfo(String packageName) {
2198 synchronized (mPackages) {
2199 WeakReference<PackageInfo> ref;
2200 ref = mPackages.get(packageName);
2201 if (ref != null && ref.get() != null) {
2202 return true;
2203 }
2204 ref = mResourcePackages.get(packageName);
2205 if (ref != null && ref.get() != null) {
2206 return true;
2207 }
2208 return false;
2209 }
2210 }
Bob Leee5408332009-09-04 18:31:17 -07002211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 ActivityThread() {
2213 }
2214
2215 public ApplicationThread getApplicationThread()
2216 {
2217 return mAppThread;
2218 }
2219
2220 public Instrumentation getInstrumentation()
2221 {
2222 return mInstrumentation;
2223 }
2224
2225 public Configuration getConfiguration() {
2226 return mConfiguration;
2227 }
2228
2229 public boolean isProfiling() {
2230 return mBoundApplication != null && mBoundApplication.profileFile != null;
2231 }
2232
2233 public String getProfileFilePath() {
2234 return mBoundApplication.profileFile;
2235 }
2236
2237 public Looper getLooper() {
2238 return mLooper;
2239 }
2240
2241 public Application getApplication() {
2242 return mInitialApplication;
2243 }
Bob Leee5408332009-09-04 18:31:17 -07002244
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002245 public String getProcessName() {
2246 return mBoundApplication.processName;
2247 }
Bob Leee5408332009-09-04 18:31:17 -07002248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 public ApplicationContext getSystemContext() {
2250 synchronized (this) {
2251 if (mSystemContext == null) {
2252 ApplicationContext context =
2253 ApplicationContext.createSystemContext(this);
Mike Cleron432b7132009-09-24 15:28:29 -07002254 PackageInfo info = new PackageInfo(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 context.init(info, null, this);
2256 context.getResources().updateConfiguration(
2257 getConfiguration(), getDisplayMetricsLocked(false));
2258 mSystemContext = context;
2259 //Log.i(TAG, "Created system resources " + context.getResources()
2260 // + ": " + context.getResources().getConfiguration());
2261 }
2262 }
2263 return mSystemContext;
2264 }
2265
Mike Cleron432b7132009-09-24 15:28:29 -07002266 public void installSystemApplicationInfo(ApplicationInfo info) {
2267 synchronized (this) {
2268 ApplicationContext context = getSystemContext();
2269 context.init(new PackageInfo(this, "android", context, info), null, this);
2270 }
2271 }
2272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 void scheduleGcIdler() {
2274 if (!mGcIdlerScheduled) {
2275 mGcIdlerScheduled = true;
2276 Looper.myQueue().addIdleHandler(mGcIdler);
2277 }
2278 mH.removeMessages(H.GC_WHEN_IDLE);
2279 }
2280
2281 void unscheduleGcIdler() {
2282 if (mGcIdlerScheduled) {
2283 mGcIdlerScheduled = false;
2284 Looper.myQueue().removeIdleHandler(mGcIdler);
2285 }
2286 mH.removeMessages(H.GC_WHEN_IDLE);
2287 }
2288
2289 void doGcIfNeeded() {
2290 mGcIdlerScheduled = false;
2291 final long now = SystemClock.uptimeMillis();
2292 //Log.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
2293 // + "m now=" + now);
2294 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
2295 //Log.i(TAG, "**** WE DO, WE DO WANT TO GC!");
2296 BinderInternal.forceGc("bg");
2297 }
2298 }
2299
2300 public final ActivityInfo resolveActivityInfo(Intent intent) {
2301 ActivityInfo aInfo = intent.resolveActivityInfo(
2302 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2303 if (aInfo == null) {
2304 // Throw an exception.
2305 Instrumentation.checkStartActivityResult(
2306 IActivityManager.START_CLASS_NOT_FOUND, intent);
2307 }
2308 return aInfo;
2309 }
Bob Leee5408332009-09-04 18:31:17 -07002310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
2313 Object lastNonConfigurationInstance) {
2314 ActivityRecord r = new ActivityRecord();
2315 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002316 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 r.intent = intent;
2318 r.state = state;
2319 r.parent = parent;
2320 r.embeddedID = id;
2321 r.activityInfo = activityInfo;
2322 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
2323 if (localLOGV) {
2324 ComponentName compname = intent.getComponent();
2325 String name;
2326 if (compname != null) {
2327 name = compname.toShortString();
2328 } else {
2329 name = "(Intent " + intent + ").getComponent() returned null";
2330 }
2331 Log.v(TAG, "Performing launch: action=" + intent.getAction()
2332 + ", comp=" + name
2333 + ", token=" + token);
2334 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07002335 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 }
2337
2338 public final Activity getActivity(IBinder token) {
2339 return mActivities.get(token).activity;
2340 }
2341
2342 public final void sendActivityResult(
2343 IBinder token, String id, int requestCode,
2344 int resultCode, Intent data) {
Chris Tate8a7dc172009-03-24 20:11:42 -07002345 if (DEBUG_RESULTS) Log.v(TAG, "sendActivityResult: id=" + id
2346 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2348 list.add(new ResultInfo(id, requestCode, resultCode, data));
2349 mAppThread.scheduleSendResult(token, list);
2350 }
2351
2352 // if the thread hasn't started yet, we don't have the handler, so just
2353 // save the messages until we're ready.
2354 private final void queueOrSendMessage(int what, Object obj) {
2355 queueOrSendMessage(what, obj, 0, 0);
2356 }
2357
2358 private final void queueOrSendMessage(int what, Object obj, int arg1) {
2359 queueOrSendMessage(what, obj, arg1, 0);
2360 }
2361
2362 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
2363 synchronized (this) {
2364 if (localLOGV) Log.v(
2365 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2366 + ": " + arg1 + " / " + obj);
2367 Message msg = Message.obtain();
2368 msg.what = what;
2369 msg.obj = obj;
2370 msg.arg1 = arg1;
2371 msg.arg2 = arg2;
2372 mH.sendMessage(msg);
2373 }
2374 }
2375
2376 final void scheduleContextCleanup(ApplicationContext context, String who,
2377 String what) {
2378 ContextCleanupInfo cci = new ContextCleanupInfo();
2379 cci.context = context;
2380 cci.who = who;
2381 cci.what = what;
2382 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
2383 }
2384
Christopher Tateb70f3df2009-04-07 16:07:59 -07002385 private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
2387
2388 ActivityInfo aInfo = r.activityInfo;
2389 if (r.packageInfo == null) {
2390 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
2391 Context.CONTEXT_INCLUDE_CODE);
2392 }
Bob Leee5408332009-09-04 18:31:17 -07002393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 ComponentName component = r.intent.getComponent();
2395 if (component == null) {
2396 component = r.intent.resolveActivity(
2397 mInitialApplication.getPackageManager());
2398 r.intent.setComponent(component);
2399 }
2400
2401 if (r.activityInfo.targetActivity != null) {
2402 component = new ComponentName(r.activityInfo.packageName,
2403 r.activityInfo.targetActivity);
2404 }
2405
2406 Activity activity = null;
2407 try {
2408 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
2409 activity = mInstrumentation.newActivity(
2410 cl, component.getClassName(), r.intent);
2411 r.intent.setExtrasClassLoader(cl);
2412 if (r.state != null) {
2413 r.state.setClassLoader(cl);
2414 }
2415 } catch (Exception e) {
2416 if (!mInstrumentation.onException(activity, e)) {
2417 throw new RuntimeException(
2418 "Unable to instantiate activity " + component
2419 + ": " + e.toString(), e);
2420 }
2421 }
2422
2423 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002424 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 if (localLOGV) Log.v(TAG, "Performing launch of " + r);
2427 if (localLOGV) Log.v(
2428 TAG, r + ": app=" + app
2429 + ", appName=" + app.getPackageName()
2430 + ", pkg=" + r.packageInfo.getPackageName()
2431 + ", comp=" + r.intent.getComponent().toShortString()
2432 + ", dir=" + r.packageInfo.getAppDir());
2433
2434 if (activity != null) {
2435 ApplicationContext appContext = new ApplicationContext();
2436 appContext.init(r.packageInfo, r.token, this);
2437 appContext.setOuterContext(activity);
2438 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
2439 Configuration config = new Configuration(mConfiguration);
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002440 if (DEBUG_CONFIGURATION) Log.v(TAG, "Launching activity "
2441 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002442 activity.attach(appContext, this, getInstrumentation(), r.token,
2443 r.ident, app, r.intent, r.activityInfo, title, r.parent,
2444 r.embeddedID, r.lastNonConfigurationInstance,
2445 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07002446
Christopher Tateb70f3df2009-04-07 16:07:59 -07002447 if (customIntent != null) {
2448 activity.mIntent = customIntent;
2449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 r.lastNonConfigurationInstance = null;
2451 r.lastNonConfigurationChildInstances = null;
2452 activity.mStartedActivity = false;
2453 int theme = r.activityInfo.getThemeResource();
2454 if (theme != 0) {
2455 activity.setTheme(theme);
2456 }
2457
2458 activity.mCalled = false;
2459 mInstrumentation.callActivityOnCreate(activity, r.state);
2460 if (!activity.mCalled) {
2461 throw new SuperNotCalledException(
2462 "Activity " + r.intent.getComponent().toShortString() +
2463 " did not call through to super.onCreate()");
2464 }
2465 r.activity = activity;
2466 r.stopped = true;
2467 if (!r.activity.mFinished) {
2468 activity.performStart();
2469 r.stopped = false;
2470 }
2471 if (!r.activity.mFinished) {
2472 if (r.state != null) {
2473 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2474 }
2475 }
2476 if (!r.activity.mFinished) {
2477 activity.mCalled = false;
2478 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2479 if (!activity.mCalled) {
2480 throw new SuperNotCalledException(
2481 "Activity " + r.intent.getComponent().toShortString() +
2482 " did not call through to super.onPostCreate()");
2483 }
2484 }
2485 r.state = null;
2486 }
2487 r.paused = true;
2488
2489 mActivities.put(r.token, r);
2490
2491 } catch (SuperNotCalledException e) {
2492 throw e;
2493
2494 } catch (Exception e) {
2495 if (!mInstrumentation.onException(activity, e)) {
2496 throw new RuntimeException(
2497 "Unable to start activity " + component
2498 + ": " + e.toString(), e);
2499 }
2500 }
2501
2502 return activity;
2503 }
2504
Christopher Tateb70f3df2009-04-07 16:07:59 -07002505 private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 // If we are getting ready to gc after going to the background, well
2507 // we are back active so skip it.
2508 unscheduleGcIdler();
2509
2510 if (localLOGV) Log.v(
2511 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002512 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513
2514 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002515 r.createdConfig = new Configuration(mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 handleResumeActivity(r.token, false, r.isForward);
2517
2518 if (!r.activity.mFinished && r.startsNotResumed) {
2519 // The activity manager actually wants this one to start out
2520 // paused, because it needs to be visible but isn't in the
2521 // foreground. We accomplish this by going through the
2522 // normal startup (because activities expect to go through
2523 // onResume() the first time they run, before their window
2524 // is displayed), and then pausing it. However, in this case
2525 // we do -not- need to do the full pause cycle (of freezing
2526 // and such) because the activity manager assumes it can just
2527 // retain the current state it has.
2528 try {
2529 r.activity.mCalled = false;
2530 mInstrumentation.callActivityOnPause(r.activity);
2531 if (!r.activity.mCalled) {
2532 throw new SuperNotCalledException(
2533 "Activity " + r.intent.getComponent().toShortString() +
2534 " did not call through to super.onPause()");
2535 }
2536
2537 } catch (SuperNotCalledException e) {
2538 throw e;
2539
2540 } catch (Exception e) {
2541 if (!mInstrumentation.onException(r.activity, e)) {
2542 throw new RuntimeException(
2543 "Unable to pause activity "
2544 + r.intent.getComponent().toShortString()
2545 + ": " + e.toString(), e);
2546 }
2547 }
2548 r.paused = true;
2549 }
2550 } else {
2551 // If there was an error, for any reason, tell the activity
2552 // manager to stop us.
2553 try {
2554 ActivityManagerNative.getDefault()
2555 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2556 } catch (RemoteException ex) {
2557 }
2558 }
2559 }
2560
2561 private final void deliverNewIntents(ActivityRecord r,
2562 List<Intent> intents) {
2563 final int N = intents.size();
2564 for (int i=0; i<N; i++) {
2565 Intent intent = intents.get(i);
2566 intent.setExtrasClassLoader(r.activity.getClassLoader());
2567 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2568 }
2569 }
2570
2571 public final void performNewIntents(IBinder token,
2572 List<Intent> intents) {
2573 ActivityRecord r = mActivities.get(token);
2574 if (r != null) {
2575 final boolean resumed = !r.paused;
2576 if (resumed) {
2577 mInstrumentation.callActivityOnPause(r.activity);
2578 }
2579 deliverNewIntents(r, intents);
2580 if (resumed) {
2581 mInstrumentation.callActivityOnResume(r.activity);
2582 }
2583 }
2584 }
Bob Leee5408332009-09-04 18:31:17 -07002585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 private final void handleNewIntent(NewIntentData data) {
2587 performNewIntents(data.token, data.intents);
2588 }
2589
2590 private final void handleReceiver(ReceiverData data) {
2591 // If we are getting ready to gc after going to the background, well
2592 // we are back active so skip it.
2593 unscheduleGcIdler();
2594
2595 String component = data.intent.getComponent().getClassName();
2596
2597 PackageInfo packageInfo = getPackageInfoNoCheck(
2598 data.info.applicationInfo);
2599
2600 IActivityManager mgr = ActivityManagerNative.getDefault();
2601
2602 BroadcastReceiver receiver = null;
2603 try {
2604 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2605 data.intent.setExtrasClassLoader(cl);
2606 if (data.resultExtras != null) {
2607 data.resultExtras.setClassLoader(cl);
2608 }
2609 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2610 } catch (Exception e) {
2611 try {
2612 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2613 data.resultData, data.resultExtras, data.resultAbort);
2614 } catch (RemoteException ex) {
2615 }
2616 throw new RuntimeException(
2617 "Unable to instantiate receiver " + component
2618 + ": " + e.toString(), e);
2619 }
2620
2621 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002622 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 if (localLOGV) Log.v(
2625 TAG, "Performing receive of " + data.intent
2626 + ": app=" + app
2627 + ", appName=" + app.getPackageName()
2628 + ", pkg=" + packageInfo.getPackageName()
2629 + ", comp=" + data.intent.getComponent().toShortString()
2630 + ", dir=" + packageInfo.getAppDir());
2631
2632 ApplicationContext context = (ApplicationContext)app.getBaseContext();
2633 receiver.setOrderedHint(true);
2634 receiver.setResult(data.resultCode, data.resultData,
2635 data.resultExtras);
2636 receiver.setOrderedHint(data.sync);
2637 receiver.onReceive(context.getReceiverRestrictedContext(),
2638 data.intent);
2639 } catch (Exception e) {
2640 try {
2641 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2642 data.resultData, data.resultExtras, data.resultAbort);
2643 } catch (RemoteException ex) {
2644 }
2645 if (!mInstrumentation.onException(receiver, e)) {
2646 throw new RuntimeException(
2647 "Unable to start receiver " + component
2648 + ": " + e.toString(), e);
2649 }
2650 }
2651
2652 try {
2653 if (data.sync) {
2654 mgr.finishReceiver(
2655 mAppThread.asBinder(), receiver.getResultCode(),
2656 receiver.getResultData(), receiver.getResultExtras(false),
2657 receiver.getAbortBroadcast());
2658 } else {
2659 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
2660 }
2661 } catch (RemoteException ex) {
2662 }
2663 }
2664
Christopher Tate181fafa2009-05-14 11:12:14 -07002665 // Instantiate a BackupAgent and tell it that it's alive
2666 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
2667 if (DEBUG_BACKUP) Log.v(TAG, "handleCreateBackupAgent: " + data);
2668
2669 // no longer idle; we have backup work to do
2670 unscheduleGcIdler();
2671
2672 // instantiate the BackupAgent class named in the manifest
2673 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2674 String packageName = packageInfo.mPackageName;
2675 if (mBackupAgents.get(packageName) != null) {
2676 Log.d(TAG, "BackupAgent " + " for " + packageName
2677 + " already exists");
2678 return;
2679 }
Bob Leee5408332009-09-04 18:31:17 -07002680
Christopher Tate181fafa2009-05-14 11:12:14 -07002681 BackupAgent agent = null;
2682 String classname = data.appInfo.backupAgentName;
2683 if (classname == null) {
2684 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
2685 Log.e(TAG, "Attempted incremental backup but no defined agent for "
2686 + packageName);
2687 return;
2688 }
2689 classname = "android.app.FullBackupAgent";
2690 }
2691 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002692 IBinder binder = null;
2693 try {
2694 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2695 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
2696
2697 // set up the agent's context
2698 if (DEBUG_BACKUP) Log.v(TAG, "Initializing BackupAgent "
2699 + data.appInfo.backupAgentName);
2700
2701 ApplicationContext context = new ApplicationContext();
2702 context.init(packageInfo, null, this);
2703 context.setOuterContext(agent);
2704 agent.attach(context);
2705
2706 agent.onCreate();
2707 binder = agent.onBind();
2708 mBackupAgents.put(packageName, agent);
2709 } catch (Exception e) {
2710 // If this is during restore, fail silently; otherwise go
2711 // ahead and let the user see the crash.
2712 Log.e(TAG, "Agent threw during creation: " + e);
2713 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
2714 throw e;
2715 }
2716 // falling through with 'binder' still null
2717 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002718
2719 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002720 try {
2721 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2722 } catch (RemoteException e) {
2723 // nothing to do.
2724 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002725 } catch (Exception e) {
2726 throw new RuntimeException("Unable to create BackupAgent "
2727 + data.appInfo.backupAgentName + ": " + e.toString(), e);
2728 }
2729 }
2730
2731 // Tear down a BackupAgent
2732 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
2733 if (DEBUG_BACKUP) Log.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002734
Christopher Tate181fafa2009-05-14 11:12:14 -07002735 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2736 String packageName = packageInfo.mPackageName;
2737 BackupAgent agent = mBackupAgents.get(packageName);
2738 if (agent != null) {
2739 try {
2740 agent.onDestroy();
2741 } catch (Exception e) {
2742 Log.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
2743 e.printStackTrace();
2744 }
2745 mBackupAgents.remove(packageName);
2746 } else {
2747 Log.w(TAG, "Attempt to destroy unknown backup agent " + data);
2748 }
2749 }
2750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 private final void handleCreateService(CreateServiceData data) {
2752 // If we are getting ready to gc after going to the background, well
2753 // we are back active so skip it.
2754 unscheduleGcIdler();
2755
2756 PackageInfo packageInfo = getPackageInfoNoCheck(
2757 data.info.applicationInfo);
2758 Service service = null;
2759 try {
2760 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2761 service = (Service) cl.loadClass(data.info.name).newInstance();
2762 } catch (Exception e) {
2763 if (!mInstrumentation.onException(service, e)) {
2764 throw new RuntimeException(
2765 "Unable to instantiate service " + data.info.name
2766 + ": " + e.toString(), e);
2767 }
2768 }
2769
2770 try {
2771 if (localLOGV) Log.v(TAG, "Creating service " + data.info.name);
2772
2773 ApplicationContext context = new ApplicationContext();
2774 context.init(packageInfo, null, this);
2775
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002776 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 context.setOuterContext(service);
2778 service.attach(context, this, data.info.name, data.token, app,
2779 ActivityManagerNative.getDefault());
2780 service.onCreate();
2781 mServices.put(data.token, service);
2782 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002783 ActivityManagerNative.getDefault().serviceDoneExecuting(
2784 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 } catch (RemoteException e) {
2786 // nothing to do.
2787 }
2788 } catch (Exception e) {
2789 if (!mInstrumentation.onException(service, e)) {
2790 throw new RuntimeException(
2791 "Unable to create service " + data.info.name
2792 + ": " + e.toString(), e);
2793 }
2794 }
2795 }
2796
2797 private final void handleBindService(BindServiceData data) {
2798 Service s = mServices.get(data.token);
2799 if (s != null) {
2800 try {
2801 data.intent.setExtrasClassLoader(s.getClassLoader());
2802 try {
2803 if (!data.rebind) {
2804 IBinder binder = s.onBind(data.intent);
2805 ActivityManagerNative.getDefault().publishService(
2806 data.token, data.intent, binder);
2807 } else {
2808 s.onRebind(data.intent);
2809 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002810 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 }
2812 } catch (RemoteException ex) {
2813 }
2814 } catch (Exception e) {
2815 if (!mInstrumentation.onException(s, e)) {
2816 throw new RuntimeException(
2817 "Unable to bind to service " + s
2818 + " with " + data.intent + ": " + e.toString(), e);
2819 }
2820 }
2821 }
2822 }
2823
2824 private final void handleUnbindService(BindServiceData data) {
2825 Service s = mServices.get(data.token);
2826 if (s != null) {
2827 try {
2828 data.intent.setExtrasClassLoader(s.getClassLoader());
2829 boolean doRebind = s.onUnbind(data.intent);
2830 try {
2831 if (doRebind) {
2832 ActivityManagerNative.getDefault().unbindFinished(
2833 data.token, data.intent, doRebind);
2834 } else {
2835 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002836 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 }
2838 } catch (RemoteException ex) {
2839 }
2840 } catch (Exception e) {
2841 if (!mInstrumentation.onException(s, e)) {
2842 throw new RuntimeException(
2843 "Unable to unbind to service " + s
2844 + " with " + data.intent + ": " + e.toString(), e);
2845 }
2846 }
2847 }
2848 }
2849
2850 private void handleDumpService(DumpServiceInfo info) {
2851 try {
2852 Service s = mServices.get(info.service);
2853 if (s != null) {
2854 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2855 s.dump(info.fd, pw, info.args);
2856 pw.close();
2857 }
2858 } finally {
2859 synchronized (info) {
2860 info.dumped = true;
2861 info.notifyAll();
2862 }
2863 }
2864 }
2865
2866 private final void handleServiceArgs(ServiceArgsData data) {
2867 Service s = mServices.get(data.token);
2868 if (s != null) {
2869 try {
2870 if (data.args != null) {
2871 data.args.setExtrasClassLoader(s.getClassLoader());
2872 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002873 int res = s.onStartCommand(data.args, data.flags, data.startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002875 ActivityManagerNative.getDefault().serviceDoneExecuting(
2876 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 } catch (RemoteException e) {
2878 // nothing to do.
2879 }
2880 } catch (Exception e) {
2881 if (!mInstrumentation.onException(s, e)) {
2882 throw new RuntimeException(
2883 "Unable to start service " + s
2884 + " with " + data.args + ": " + e.toString(), e);
2885 }
2886 }
2887 }
2888 }
2889
2890 private final void handleStopService(IBinder token) {
2891 Service s = mServices.remove(token);
2892 if (s != null) {
2893 try {
2894 if (localLOGV) Log.v(TAG, "Destroying service " + s);
2895 s.onDestroy();
2896 Context context = s.getBaseContext();
2897 if (context instanceof ApplicationContext) {
2898 final String who = s.getClassName();
2899 ((ApplicationContext) context).scheduleFinalCleanup(who, "Service");
2900 }
2901 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002902 ActivityManagerNative.getDefault().serviceDoneExecuting(
2903 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 } catch (RemoteException e) {
2905 // nothing to do.
2906 }
2907 } catch (Exception e) {
2908 if (!mInstrumentation.onException(s, e)) {
2909 throw new RuntimeException(
2910 "Unable to stop service " + s
2911 + ": " + e.toString(), e);
2912 }
2913 }
2914 }
2915 //Log.i(TAG, "Running services: " + mServices);
2916 }
2917
2918 public final ActivityRecord performResumeActivity(IBinder token,
2919 boolean clearHide) {
2920 ActivityRecord r = mActivities.get(token);
2921 if (localLOGV) Log.v(TAG, "Performing resume of " + r
2922 + " finished=" + r.activity.mFinished);
2923 if (r != null && !r.activity.mFinished) {
2924 if (clearHide) {
2925 r.hideForNow = false;
2926 r.activity.mStartedActivity = false;
2927 }
2928 try {
2929 if (r.pendingIntents != null) {
2930 deliverNewIntents(r, r.pendingIntents);
2931 r.pendingIntents = null;
2932 }
2933 if (r.pendingResults != null) {
2934 deliverResults(r, r.pendingResults);
2935 r.pendingResults = null;
2936 }
2937 r.activity.performResume();
2938
Bob Leee5408332009-09-04 18:31:17 -07002939 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 r.paused = false;
2943 r.stopped = false;
2944 if (r.activity.mStartedActivity) {
2945 r.hideForNow = true;
2946 }
2947 r.state = null;
2948 } catch (Exception e) {
2949 if (!mInstrumentation.onException(r.activity, e)) {
2950 throw new RuntimeException(
2951 "Unable to resume activity "
2952 + r.intent.getComponent().toShortString()
2953 + ": " + e.toString(), e);
2954 }
2955 }
2956 }
2957 return r;
2958 }
2959
2960 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2961 // If we are getting ready to gc after going to the background, well
2962 // we are back active so skip it.
2963 unscheduleGcIdler();
2964
2965 ActivityRecord r = performResumeActivity(token, clearHide);
2966
2967 if (r != null) {
2968 final Activity a = r.activity;
2969
2970 if (localLOGV) Log.v(
2971 TAG, "Resume " + r + " started activity: " +
2972 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2973 + ", finished: " + a.mFinished);
2974
2975 final int forwardBit = isForward ?
2976 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 // If the window hasn't yet been added to the window manager,
2979 // and this guy didn't finish itself or start another activity,
2980 // then go ahead and add the window.
2981 if (r.window == null && !a.mFinished && !a.mStartedActivity) {
2982 r.window = r.activity.getWindow();
2983 View decor = r.window.getDecorView();
2984 decor.setVisibility(View.INVISIBLE);
2985 ViewManager wm = a.getWindowManager();
2986 WindowManager.LayoutParams l = r.window.getAttributes();
2987 a.mDecor = decor;
2988 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2989 l.softInputMode |= forwardBit;
2990 if (a.mVisibleFromClient) {
2991 a.mWindowAdded = true;
2992 wm.addView(decor, l);
2993 }
2994
2995 // If the window has already been added, but during resume
2996 // we started another activity, then don't yet make the
2997 // window visisble.
2998 } else if (a.mStartedActivity) {
2999 if (localLOGV) Log.v(
3000 TAG, "Launch " + r + " mStartedActivity set");
3001 r.hideForNow = true;
3002 }
3003
3004 // The window is now visible if it has been added, we are not
3005 // simply finishing, and we are not starting another activity.
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003006 if (!r.activity.mFinished && !a.mStartedActivity
3007 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 if (r.newConfig != null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003009 if (DEBUG_CONFIGURATION) Log.v(TAG, "Resuming activity "
3010 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 performConfigurationChanged(r.activity, r.newConfig);
3012 r.newConfig = null;
3013 }
3014 if (localLOGV) Log.v(TAG, "Resuming " + r + " with isForward="
3015 + isForward);
3016 WindowManager.LayoutParams l = r.window.getAttributes();
3017 if ((l.softInputMode
3018 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
3019 != forwardBit) {
3020 l.softInputMode = (l.softInputMode
3021 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
3022 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003023 if (r.activity.mVisibleFromClient) {
3024 ViewManager wm = a.getWindowManager();
3025 View decor = r.window.getDecorView();
3026 wm.updateViewLayout(decor, l);
3027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 }
3029 r.activity.mVisibleFromServer = true;
3030 mNumVisibleActivities++;
3031 if (r.activity.mVisibleFromClient) {
3032 r.activity.makeVisible();
3033 }
3034 }
3035
3036 r.nextIdle = mNewActivities;
3037 mNewActivities = r;
3038 if (localLOGV) Log.v(
3039 TAG, "Scheduling idle handler for " + r);
3040 Looper.myQueue().addIdleHandler(new Idler());
3041
3042 } else {
3043 // If an exception was thrown when trying to resume, then
3044 // just end this activity.
3045 try {
3046 ActivityManagerNative.getDefault()
3047 .finishActivity(token, Activity.RESULT_CANCELED, null);
3048 } catch (RemoteException ex) {
3049 }
3050 }
3051 }
3052
3053 private int mThumbnailWidth = -1;
3054 private int mThumbnailHeight = -1;
3055
3056 private final Bitmap createThumbnailBitmap(ActivityRecord r) {
3057 Bitmap thumbnail = null;
3058 try {
3059 int w = mThumbnailWidth;
3060 int h;
3061 if (w < 0) {
3062 Resources res = r.activity.getResources();
3063 mThumbnailHeight = h =
3064 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
3065
3066 mThumbnailWidth = w =
3067 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
3068 } else {
3069 h = mThumbnailHeight;
3070 }
3071
3072 // XXX Only set hasAlpha if needed?
3073 thumbnail = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
3074 thumbnail.eraseColor(0);
3075 Canvas cv = new Canvas(thumbnail);
3076 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
3077 thumbnail = null;
3078 }
3079 } catch (Exception e) {
3080 if (!mInstrumentation.onException(r.activity, e)) {
3081 throw new RuntimeException(
3082 "Unable to create thumbnail of "
3083 + r.intent.getComponent().toShortString()
3084 + ": " + e.toString(), e);
3085 }
3086 thumbnail = null;
3087 }
3088
3089 return thumbnail;
3090 }
3091
3092 private final void handlePauseActivity(IBinder token, boolean finished,
3093 boolean userLeaving, int configChanges) {
3094 ActivityRecord r = mActivities.get(token);
3095 if (r != null) {
3096 //Log.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
3097 if (userLeaving) {
3098 performUserLeavingActivity(r);
3099 }
Bob Leee5408332009-09-04 18:31:17 -07003100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 r.activity.mConfigChangeFlags |= configChanges;
3102 Bundle state = performPauseActivity(token, finished, true);
3103
3104 // Tell the activity manager we have paused.
3105 try {
3106 ActivityManagerNative.getDefault().activityPaused(token, state);
3107 } catch (RemoteException ex) {
3108 }
3109 }
3110 }
3111
3112 final void performUserLeavingActivity(ActivityRecord r) {
3113 mInstrumentation.callActivityOnUserLeaving(r.activity);
3114 }
3115
3116 final Bundle performPauseActivity(IBinder token, boolean finished,
3117 boolean saveState) {
3118 ActivityRecord r = mActivities.get(token);
3119 return r != null ? performPauseActivity(r, finished, saveState) : null;
3120 }
3121
3122 final Bundle performPauseActivity(ActivityRecord r, boolean finished,
3123 boolean saveState) {
3124 if (r.paused) {
3125 if (r.activity.mFinished) {
3126 // If we are finishing, we won't call onResume() in certain cases.
3127 // So here we likewise don't want to call onPause() if the activity
3128 // isn't resumed.
3129 return null;
3130 }
3131 RuntimeException e = new RuntimeException(
3132 "Performing pause of activity that is not resumed: "
3133 + r.intent.getComponent().toShortString());
3134 Log.e(TAG, e.getMessage(), e);
3135 }
3136 Bundle state = null;
3137 if (finished) {
3138 r.activity.mFinished = true;
3139 }
3140 try {
3141 // Next have the activity save its current state and managed dialogs...
3142 if (!r.activity.mFinished && saveState) {
3143 state = new Bundle();
3144 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
3145 r.state = state;
3146 }
3147 // Now we are idle.
3148 r.activity.mCalled = false;
3149 mInstrumentation.callActivityOnPause(r.activity);
3150 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
3151 if (!r.activity.mCalled) {
3152 throw new SuperNotCalledException(
3153 "Activity " + r.intent.getComponent().toShortString() +
3154 " did not call through to super.onPause()");
3155 }
3156
3157 } catch (SuperNotCalledException e) {
3158 throw e;
3159
3160 } catch (Exception e) {
3161 if (!mInstrumentation.onException(r.activity, e)) {
3162 throw new RuntimeException(
3163 "Unable to pause activity "
3164 + r.intent.getComponent().toShortString()
3165 + ": " + e.toString(), e);
3166 }
3167 }
3168 r.paused = true;
3169 return state;
3170 }
3171
3172 final void performStopActivity(IBinder token) {
3173 ActivityRecord r = mActivities.get(token);
3174 performStopActivityInner(r, null, false);
3175 }
3176
3177 private static class StopInfo {
3178 Bitmap thumbnail;
3179 CharSequence description;
3180 }
3181
3182 private final class ProviderRefCount {
3183 public int count;
3184 ProviderRefCount(int pCount) {
3185 count = pCount;
3186 }
3187 }
3188
3189 private final void performStopActivityInner(ActivityRecord r,
3190 StopInfo info, boolean keepShown) {
3191 if (localLOGV) Log.v(TAG, "Performing stop of " + r);
3192 if (r != null) {
3193 if (!keepShown && r.stopped) {
3194 if (r.activity.mFinished) {
3195 // If we are finishing, we won't call onResume() in certain
3196 // cases. So here we likewise don't want to call onStop()
3197 // if the activity isn't resumed.
3198 return;
3199 }
3200 RuntimeException e = new RuntimeException(
3201 "Performing stop of activity that is not resumed: "
3202 + r.intent.getComponent().toShortString());
3203 Log.e(TAG, e.getMessage(), e);
3204 }
3205
3206 if (info != null) {
3207 try {
3208 // First create a thumbnail for the activity...
3209 //info.thumbnail = createThumbnailBitmap(r);
3210 info.description = r.activity.onCreateDescription();
3211 } catch (Exception e) {
3212 if (!mInstrumentation.onException(r.activity, e)) {
3213 throw new RuntimeException(
3214 "Unable to save state of activity "
3215 + r.intent.getComponent().toShortString()
3216 + ": " + e.toString(), e);
3217 }
3218 }
3219 }
3220
3221 if (!keepShown) {
3222 try {
3223 // Now we are idle.
3224 r.activity.performStop();
3225 } catch (Exception e) {
3226 if (!mInstrumentation.onException(r.activity, e)) {
3227 throw new RuntimeException(
3228 "Unable to stop activity "
3229 + r.intent.getComponent().toShortString()
3230 + ": " + e.toString(), e);
3231 }
3232 }
3233 r.stopped = true;
3234 }
3235
3236 r.paused = true;
3237 }
3238 }
3239
3240 private final void updateVisibility(ActivityRecord r, boolean show) {
3241 View v = r.activity.mDecor;
3242 if (v != null) {
3243 if (show) {
3244 if (!r.activity.mVisibleFromServer) {
3245 r.activity.mVisibleFromServer = true;
3246 mNumVisibleActivities++;
3247 if (r.activity.mVisibleFromClient) {
3248 r.activity.makeVisible();
3249 }
3250 }
3251 if (r.newConfig != null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003252 if (DEBUG_CONFIGURATION) Log.v(TAG, "Updating activity vis "
3253 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 performConfigurationChanged(r.activity, r.newConfig);
3255 r.newConfig = null;
3256 }
3257 } else {
3258 if (r.activity.mVisibleFromServer) {
3259 r.activity.mVisibleFromServer = false;
3260 mNumVisibleActivities--;
3261 v.setVisibility(View.INVISIBLE);
3262 }
3263 }
3264 }
3265 }
3266
3267 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
3268 ActivityRecord r = mActivities.get(token);
3269 r.activity.mConfigChangeFlags |= configChanges;
3270
3271 StopInfo info = new StopInfo();
3272 performStopActivityInner(r, info, show);
3273
3274 if (localLOGV) Log.v(
3275 TAG, "Finishing stop of " + r + ": show=" + show
3276 + " win=" + r.window);
3277
3278 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07003279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 // Tell activity manager we have been stopped.
3281 try {
3282 ActivityManagerNative.getDefault().activityStopped(
3283 r.token, info.thumbnail, info.description);
3284 } catch (RemoteException ex) {
3285 }
3286 }
3287
3288 final void performRestartActivity(IBinder token) {
3289 ActivityRecord r = mActivities.get(token);
3290 if (r.stopped) {
3291 r.activity.performRestart();
3292 r.stopped = false;
3293 }
3294 }
3295
3296 private final void handleWindowVisibility(IBinder token, boolean show) {
3297 ActivityRecord r = mActivities.get(token);
3298 if (!show && !r.stopped) {
3299 performStopActivityInner(r, null, show);
3300 } else if (show && r.stopped) {
3301 // If we are getting ready to gc after going to the background, well
3302 // we are back active so skip it.
3303 unscheduleGcIdler();
3304
3305 r.activity.performRestart();
3306 r.stopped = false;
3307 }
3308 if (r.activity.mDecor != null) {
3309 if (Config.LOGV) Log.v(
3310 TAG, "Handle window " + r + " visibility: " + show);
3311 updateVisibility(r, show);
3312 }
3313 }
3314
3315 private final void deliverResults(ActivityRecord r, List<ResultInfo> results) {
3316 final int N = results.size();
3317 for (int i=0; i<N; i++) {
3318 ResultInfo ri = results.get(i);
3319 try {
3320 if (ri.mData != null) {
3321 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3322 }
Chris Tate8a7dc172009-03-24 20:11:42 -07003323 if (DEBUG_RESULTS) Log.v(TAG,
3324 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 r.activity.dispatchActivityResult(ri.mResultWho,
3326 ri.mRequestCode, ri.mResultCode, ri.mData);
3327 } catch (Exception e) {
3328 if (!mInstrumentation.onException(r.activity, e)) {
3329 throw new RuntimeException(
3330 "Failure delivering result " + ri + " to activity "
3331 + r.intent.getComponent().toShortString()
3332 + ": " + e.toString(), e);
3333 }
3334 }
3335 }
3336 }
3337
3338 private final void handleSendResult(ResultData res) {
3339 ActivityRecord r = mActivities.get(res.token);
Chris Tate8a7dc172009-03-24 20:11:42 -07003340 if (DEBUG_RESULTS) Log.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 if (r != null) {
3342 final boolean resumed = !r.paused;
3343 if (!r.activity.mFinished && r.activity.mDecor != null
3344 && r.hideForNow && resumed) {
3345 // We had hidden the activity because it started another
3346 // one... we have gotten a result back and we are not
3347 // paused, so make sure our window is visible.
3348 updateVisibility(r, true);
3349 }
3350 if (resumed) {
3351 try {
3352 // Now we are idle.
3353 r.activity.mCalled = false;
3354 mInstrumentation.callActivityOnPause(r.activity);
3355 if (!r.activity.mCalled) {
3356 throw new SuperNotCalledException(
3357 "Activity " + r.intent.getComponent().toShortString()
3358 + " did not call through to super.onPause()");
3359 }
3360 } catch (SuperNotCalledException e) {
3361 throw e;
3362 } catch (Exception e) {
3363 if (!mInstrumentation.onException(r.activity, e)) {
3364 throw new RuntimeException(
3365 "Unable to pause activity "
3366 + r.intent.getComponent().toShortString()
3367 + ": " + e.toString(), e);
3368 }
3369 }
3370 }
3371 deliverResults(r, res.results);
3372 if (resumed) {
3373 mInstrumentation.callActivityOnResume(r.activity);
3374 }
3375 }
3376 }
3377
3378 public final ActivityRecord performDestroyActivity(IBinder token, boolean finishing) {
3379 return performDestroyActivity(token, finishing, 0, false);
3380 }
3381
3382 private final ActivityRecord performDestroyActivity(IBinder token, boolean finishing,
3383 int configChanges, boolean getNonConfigInstance) {
3384 ActivityRecord r = mActivities.get(token);
3385 if (localLOGV) Log.v(TAG, "Performing finish of " + r);
3386 if (r != null) {
3387 r.activity.mConfigChangeFlags |= configChanges;
3388 if (finishing) {
3389 r.activity.mFinished = true;
3390 }
3391 if (!r.paused) {
3392 try {
3393 r.activity.mCalled = false;
3394 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003395 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 r.activity.getComponentName().getClassName());
3397 if (!r.activity.mCalled) {
3398 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003399 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 + " did not call through to super.onPause()");
3401 }
3402 } catch (SuperNotCalledException e) {
3403 throw e;
3404 } catch (Exception e) {
3405 if (!mInstrumentation.onException(r.activity, e)) {
3406 throw new RuntimeException(
3407 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003408 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 + ": " + e.toString(), e);
3410 }
3411 }
3412 r.paused = true;
3413 }
3414 if (!r.stopped) {
3415 try {
3416 r.activity.performStop();
3417 } catch (SuperNotCalledException e) {
3418 throw e;
3419 } catch (Exception e) {
3420 if (!mInstrumentation.onException(r.activity, e)) {
3421 throw new RuntimeException(
3422 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003423 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 + ": " + e.toString(), e);
3425 }
3426 }
3427 r.stopped = true;
3428 }
3429 if (getNonConfigInstance) {
3430 try {
3431 r.lastNonConfigurationInstance
3432 = r.activity.onRetainNonConfigurationInstance();
3433 } catch (Exception e) {
3434 if (!mInstrumentation.onException(r.activity, e)) {
3435 throw new RuntimeException(
3436 "Unable to retain activity "
3437 + r.intent.getComponent().toShortString()
3438 + ": " + e.toString(), e);
3439 }
3440 }
3441 try {
3442 r.lastNonConfigurationChildInstances
3443 = r.activity.onRetainNonConfigurationChildInstances();
3444 } catch (Exception e) {
3445 if (!mInstrumentation.onException(r.activity, e)) {
3446 throw new RuntimeException(
3447 "Unable to retain child activities "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003448 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 + ": " + e.toString(), e);
3450 }
3451 }
Bob Leee5408332009-09-04 18:31:17 -07003452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 }
3454 try {
3455 r.activity.mCalled = false;
3456 r.activity.onDestroy();
3457 if (!r.activity.mCalled) {
3458 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003459 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 " did not call through to super.onDestroy()");
3461 }
3462 if (r.window != null) {
3463 r.window.closeAllPanels();
3464 }
3465 } catch (SuperNotCalledException e) {
3466 throw e;
3467 } catch (Exception e) {
3468 if (!mInstrumentation.onException(r.activity, e)) {
3469 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003470 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3471 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 }
3473 }
3474 }
3475 mActivities.remove(token);
3476
3477 return r;
3478 }
3479
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003480 private static String safeToComponentShortString(Intent intent) {
3481 ComponentName component = intent.getComponent();
3482 return component == null ? "[Unknown]" : component.toShortString();
3483 }
3484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 private final void handleDestroyActivity(IBinder token, boolean finishing,
3486 int configChanges, boolean getNonConfigInstance) {
3487 ActivityRecord r = performDestroyActivity(token, finishing,
3488 configChanges, getNonConfigInstance);
3489 if (r != null) {
3490 WindowManager wm = r.activity.getWindowManager();
3491 View v = r.activity.mDecor;
3492 if (v != null) {
3493 if (r.activity.mVisibleFromServer) {
3494 mNumVisibleActivities--;
3495 }
3496 IBinder wtoken = v.getWindowToken();
3497 if (r.activity.mWindowAdded) {
3498 wm.removeViewImmediate(v);
3499 }
3500 if (wtoken != null) {
3501 WindowManagerImpl.getDefault().closeAll(wtoken,
3502 r.activity.getClass().getName(), "Activity");
3503 }
3504 r.activity.mDecor = null;
3505 }
3506 WindowManagerImpl.getDefault().closeAll(token,
3507 r.activity.getClass().getName(), "Activity");
3508
3509 // Mocked out contexts won't be participating in the normal
3510 // process lifecycle, but if we're running with a proper
3511 // ApplicationContext we need to have it tear down things
3512 // cleanly.
3513 Context c = r.activity.getBaseContext();
3514 if (c instanceof ApplicationContext) {
3515 ((ApplicationContext) c).scheduleFinalCleanup(
3516 r.activity.getClass().getName(), "Activity");
3517 }
3518 }
3519 if (finishing) {
3520 try {
3521 ActivityManagerNative.getDefault().activityDestroyed(token);
3522 } catch (RemoteException ex) {
3523 // If the system process has died, it's game over for everyone.
3524 }
3525 }
3526 }
3527
3528 private final void handleRelaunchActivity(ActivityRecord tmp, int configChanges) {
3529 // If we are getting ready to gc after going to the background, well
3530 // we are back active so skip it.
3531 unscheduleGcIdler();
3532
3533 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07003534
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003535 if (DEBUG_CONFIGURATION) Log.v(TAG, "Relaunching activity "
3536 + tmp.token + " with configChanges=0x"
3537 + Integer.toHexString(configChanges));
3538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 // First: make sure we have the most recent configuration and most
3540 // recent version of the activity, or skip it if some previous call
3541 // had taken a more recent version.
3542 synchronized (mRelaunchingActivities) {
3543 int N = mRelaunchingActivities.size();
3544 IBinder token = tmp.token;
3545 tmp = null;
3546 for (int i=0; i<N; i++) {
3547 ActivityRecord r = mRelaunchingActivities.get(i);
3548 if (r.token == token) {
3549 tmp = r;
3550 mRelaunchingActivities.remove(i);
3551 i--;
3552 N--;
3553 }
3554 }
Bob Leee5408332009-09-04 18:31:17 -07003555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 if (tmp == null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003557 if (DEBUG_CONFIGURATION) Log.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 return;
3559 }
Bob Leee5408332009-09-04 18:31:17 -07003560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 if (mPendingConfiguration != null) {
3562 changedConfig = mPendingConfiguration;
3563 mPendingConfiguration = null;
3564 }
3565 }
Bob Leee5408332009-09-04 18:31:17 -07003566
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003567 if (tmp.createdConfig != null) {
3568 // If the activity manager is passing us its current config,
3569 // assume that is really what we want regardless of what we
3570 // may have pending.
3571 if (mConfiguration == null
3572 || mConfiguration.diff(tmp.createdConfig) != 0) {
3573 changedConfig = tmp.createdConfig;
3574 }
3575 }
3576
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003577 if (DEBUG_CONFIGURATION) Log.v(TAG, "Relaunching activity "
3578 + tmp.token + ": changedConfig=" + changedConfig);
3579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 // If there was a pending configuration change, execute it first.
3581 if (changedConfig != null) {
3582 handleConfigurationChanged(changedConfig);
3583 }
Bob Leee5408332009-09-04 18:31:17 -07003584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 ActivityRecord r = mActivities.get(tmp.token);
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003586 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 if (r == null) {
3588 return;
3589 }
Bob Leee5408332009-09-04 18:31:17 -07003590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003592 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 Bundle savedState = null;
3595 if (!r.paused) {
3596 savedState = performPauseActivity(r.token, false, true);
3597 }
Bob Leee5408332009-09-04 18:31:17 -07003598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 r.activity = null;
3602 r.window = null;
3603 r.hideForNow = false;
3604 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003605 // Merge any pending results and pending intents; don't just replace them
3606 if (tmp.pendingResults != null) {
3607 if (r.pendingResults == null) {
3608 r.pendingResults = tmp.pendingResults;
3609 } else {
3610 r.pendingResults.addAll(tmp.pendingResults);
3611 }
3612 }
3613 if (tmp.pendingIntents != null) {
3614 if (r.pendingIntents == null) {
3615 r.pendingIntents = tmp.pendingIntents;
3616 } else {
3617 r.pendingIntents.addAll(tmp.pendingIntents);
3618 }
3619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 r.startsNotResumed = tmp.startsNotResumed;
3621 if (savedState != null) {
3622 r.state = savedState;
3623 }
Bob Leee5408332009-09-04 18:31:17 -07003624
Christopher Tateb70f3df2009-04-07 16:07:59 -07003625 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 }
3627
3628 private final void handleRequestThumbnail(IBinder token) {
3629 ActivityRecord r = mActivities.get(token);
3630 Bitmap thumbnail = createThumbnailBitmap(r);
3631 CharSequence description = null;
3632 try {
3633 description = r.activity.onCreateDescription();
3634 } catch (Exception e) {
3635 if (!mInstrumentation.onException(r.activity, e)) {
3636 throw new RuntimeException(
3637 "Unable to create description of activity "
3638 + r.intent.getComponent().toShortString()
3639 + ": " + e.toString(), e);
3640 }
3641 }
3642 //System.out.println("Reporting top thumbnail " + thumbnail);
3643 try {
3644 ActivityManagerNative.getDefault().reportThumbnail(
3645 token, thumbnail, description);
3646 } catch (RemoteException ex) {
3647 }
3648 }
3649
3650 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
3651 boolean allActivities, Configuration newConfig) {
3652 ArrayList<ComponentCallbacks> callbacks
3653 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 if (mActivities.size() > 0) {
3656 Iterator<ActivityRecord> it = mActivities.values().iterator();
3657 while (it.hasNext()) {
3658 ActivityRecord ar = it.next();
3659 Activity a = ar.activity;
3660 if (a != null) {
3661 if (!ar.activity.mFinished && (allActivities ||
3662 (a != null && !ar.paused))) {
3663 // If the activity is currently resumed, its configuration
3664 // needs to change right now.
3665 callbacks.add(a);
3666 } else if (newConfig != null) {
3667 // Otherwise, we will tell it about the change
3668 // the next time it is resumed or shown. Note that
3669 // the activity manager may, before then, decide the
3670 // activity needs to be destroyed to handle its new
3671 // configuration.
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003672 if (DEBUG_CONFIGURATION) Log.v(TAG, "Setting activity "
3673 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 ar.newConfig = newConfig;
3675 }
3676 }
3677 }
3678 }
3679 if (mServices.size() > 0) {
3680 Iterator<Service> it = mServices.values().iterator();
3681 while (it.hasNext()) {
3682 callbacks.add(it.next());
3683 }
3684 }
3685 synchronized (mProviderMap) {
3686 if (mLocalProviders.size() > 0) {
3687 Iterator<ProviderRecord> it = mLocalProviders.values().iterator();
3688 while (it.hasNext()) {
3689 callbacks.add(it.next().mLocalProvider);
3690 }
3691 }
3692 }
3693 final int N = mAllApplications.size();
3694 for (int i=0; i<N; i++) {
3695 callbacks.add(mAllApplications.get(i));
3696 }
Bob Leee5408332009-09-04 18:31:17 -07003697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 return callbacks;
3699 }
Bob Leee5408332009-09-04 18:31:17 -07003700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 private final void performConfigurationChanged(
3702 ComponentCallbacks cb, Configuration config) {
3703 // Only for Activity objects, check that they actually call up to their
3704 // superclass implementation. ComponentCallbacks is an interface, so
3705 // we check the runtime type and act accordingly.
3706 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3707 if (activity != null) {
3708 activity.mCalled = false;
3709 }
Bob Leee5408332009-09-04 18:31:17 -07003710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 boolean shouldChangeConfig = false;
3712 if ((activity == null) || (activity.mCurrentConfig == null)) {
3713 shouldChangeConfig = true;
3714 } else {
Bob Leee5408332009-09-04 18:31:17 -07003715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 // If the new config is the same as the config this Activity
3717 // is already running with then don't bother calling
3718 // onConfigurationChanged
3719 int diff = activity.mCurrentConfig.diff(config);
3720 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07003721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 // If this activity doesn't handle any of the config changes
3723 // then don't bother calling onConfigurationChanged as we're
3724 // going to destroy it.
3725 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
3726 shouldChangeConfig = true;
3727 }
3728 }
3729 }
Bob Leee5408332009-09-04 18:31:17 -07003730
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003731 if (DEBUG_CONFIGURATION) Log.v(TAG, "Config callback " + cb
3732 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 if (shouldChangeConfig) {
3734 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 if (activity != null) {
3737 if (!activity.mCalled) {
3738 throw new SuperNotCalledException(
3739 "Activity " + activity.getLocalClassName() +
3740 " did not call through to super.onConfigurationChanged()");
3741 }
3742 activity.mConfigChangeFlags = 0;
3743 activity.mCurrentConfig = new Configuration(config);
3744 }
3745 }
3746 }
3747
3748 final void handleConfigurationChanged(Configuration config) {
Bob Leee5408332009-09-04 18:31:17 -07003749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 synchronized (mRelaunchingActivities) {
3751 if (mPendingConfiguration != null) {
3752 config = mPendingConfiguration;
3753 mPendingConfiguration = null;
3754 }
3755 }
Bob Leee5408332009-09-04 18:31:17 -07003756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 ArrayList<ComponentCallbacks> callbacks
3758 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003759
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003760 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handle configuration changed: "
3761 + config);
3762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 synchronized(mPackages) {
3764 if (mConfiguration == null) {
3765 mConfiguration = new Configuration();
3766 }
3767 mConfiguration.updateFrom(config);
3768 DisplayMetrics dm = getDisplayMetricsLocked(true);
3769
3770 // set it for java, this also affects newly created Resources
3771 if (config.locale != null) {
3772 Locale.setDefault(config.locale);
3773 }
3774
Dianne Hackborn0d907fa2009-07-27 20:48:50 -07003775 Resources.updateSystemConfiguration(config, dm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776
3777 ApplicationContext.ApplicationPackageManager.configurationChanged();
3778 //Log.i(TAG, "Configuration changed in " + currentPackageName());
3779 {
3780 Iterator<WeakReference<Resources>> it =
3781 mActiveResources.values().iterator();
3782 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3783 // mActiveResources.entrySet().iterator();
3784 while (it.hasNext()) {
3785 WeakReference<Resources> v = it.next();
3786 Resources r = v.get();
3787 if (r != null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003788 r.updateConfiguration(config, dm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 //Log.i(TAG, "Updated app resources " + v.getKey()
3790 // + " " + r + ": " + r.getConfiguration());
3791 } else {
3792 //Log.i(TAG, "Removing old resources " + v.getKey());
3793 it.remove();
3794 }
3795 }
3796 }
Bob Leee5408332009-09-04 18:31:17 -07003797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 callbacks = collectComponentCallbacksLocked(false, config);
3799 }
Bob Leee5408332009-09-04 18:31:17 -07003800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 final int N = callbacks.size();
3802 for (int i=0; i<N; i++) {
3803 performConfigurationChanged(callbacks.get(i), config);
3804 }
3805 }
3806
3807 final void handleActivityConfigurationChanged(IBinder token) {
3808 ActivityRecord r = mActivities.get(token);
3809 if (r == null || r.activity == null) {
3810 return;
3811 }
Bob Leee5408332009-09-04 18:31:17 -07003812
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003813 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handle activity config changed: "
3814 + r.activityInfo.name);
3815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 performConfigurationChanged(r.activity, mConfiguration);
3817 }
3818
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003819 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003820 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003821 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003822 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3823 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003824 } catch (RuntimeException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003825 Log.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003826 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003827 } finally {
3828 try {
3829 pcd.fd.close();
3830 } catch (IOException e) {
3831 Log.w(TAG, "Failure closing profile fd", e);
3832 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003833 }
3834 } else {
3835 Debug.stopMethodTracing();
3836 }
3837 }
Bob Leee5408332009-09-04 18:31:17 -07003838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 final void handleLowMemory() {
3840 ArrayList<ComponentCallbacks> callbacks
3841 = new ArrayList<ComponentCallbacks>();
3842
3843 synchronized(mPackages) {
3844 callbacks = collectComponentCallbacksLocked(true, null);
3845 }
Bob Leee5408332009-09-04 18:31:17 -07003846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 final int N = callbacks.size();
3848 for (int i=0; i<N; i++) {
3849 callbacks.get(i).onLowMemory();
3850 }
3851
Chris Tatece229052009-03-25 16:44:52 -07003852 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3853 if (Process.myUid() != Process.SYSTEM_UID) {
3854 int sqliteReleased = SQLiteDatabase.releaseMemory();
3855 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3856 }
Bob Leee5408332009-09-04 18:31:17 -07003857
Mike Reedcaf0df12009-04-27 14:32:05 -04003858 // Ask graphics to free up as much as possible (font/image caches)
3859 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860
3861 BinderInternal.forceGc("mem");
3862 }
3863
3864 private final void handleBindApplication(AppBindData data) {
3865 mBoundApplication = data;
3866 mConfiguration = new Configuration(data.config);
3867
3868 // We now rely on this being set by zygote.
3869 //Process.setGid(data.appInfo.gid);
3870 //Process.setUid(data.appInfo.uid);
3871
3872 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003873 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 android.ddm.DdmHandleAppName.setAppName(data.processName);
3875
3876 /*
3877 * Before spawning a new process, reset the time zone to be the system time zone.
3878 * This needs to be done because the system time zone could have changed after the
3879 * the spawning of this process. Without doing this this process would have the incorrect
3880 * system time zone.
3881 */
3882 TimeZone.setDefault(null);
3883
3884 /*
3885 * Initialize the default locale in this process for the reasons we set the time zone.
3886 */
3887 Locale.setDefault(data.config.locale);
3888
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003889 /*
3890 * Update the system configuration since its preloaded and might not
3891 * reflect configuration changes. The configuration object passed
3892 * in AppBindData can be safely assumed to be up to date
3893 */
3894 Resources.getSystem().updateConfiguration(mConfiguration, null);
3895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 data.info = getPackageInfoNoCheck(data.appInfo);
3897
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003898 /**
3899 * Switch this process to density compatibility mode if needed.
3900 */
3901 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3902 == 0) {
3903 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3904 }
Bob Leee5408332009-09-04 18:31:17 -07003905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3907 // XXX should have option to change the port.
3908 Debug.changeDebugPort(8100);
3909 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
3910 Log.w(TAG, "Application " + data.info.getPackageName()
3911 + " is waiting for the debugger on port 8100...");
3912
3913 IActivityManager mgr = ActivityManagerNative.getDefault();
3914 try {
3915 mgr.showWaitingForDebugger(mAppThread, true);
3916 } catch (RemoteException ex) {
3917 }
3918
3919 Debug.waitForDebugger();
3920
3921 try {
3922 mgr.showWaitingForDebugger(mAppThread, false);
3923 } catch (RemoteException ex) {
3924 }
3925
3926 } else {
3927 Log.w(TAG, "Application " + data.info.getPackageName()
3928 + " can be debugged on port 8100...");
3929 }
3930 }
3931
3932 if (data.instrumentationName != null) {
3933 ApplicationContext appContext = new ApplicationContext();
3934 appContext.init(data.info, null, this);
3935 InstrumentationInfo ii = null;
3936 try {
3937 ii = appContext.getPackageManager().
3938 getInstrumentationInfo(data.instrumentationName, 0);
3939 } catch (PackageManager.NameNotFoundException e) {
3940 }
3941 if (ii == null) {
3942 throw new RuntimeException(
3943 "Unable to find instrumentation info for: "
3944 + data.instrumentationName);
3945 }
3946
3947 mInstrumentationAppDir = ii.sourceDir;
3948 mInstrumentationAppPackage = ii.packageName;
3949 mInstrumentedAppDir = data.info.getAppDir();
3950
3951 ApplicationInfo instrApp = new ApplicationInfo();
3952 instrApp.packageName = ii.packageName;
3953 instrApp.sourceDir = ii.sourceDir;
3954 instrApp.publicSourceDir = ii.publicSourceDir;
3955 instrApp.dataDir = ii.dataDir;
3956 PackageInfo pi = getPackageInfo(instrApp,
3957 appContext.getClassLoader(), false, true);
3958 ApplicationContext instrContext = new ApplicationContext();
3959 instrContext.init(pi, null, this);
3960
3961 try {
3962 java.lang.ClassLoader cl = instrContext.getClassLoader();
3963 mInstrumentation = (Instrumentation)
3964 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3965 } catch (Exception e) {
3966 throw new RuntimeException(
3967 "Unable to instantiate instrumentation "
3968 + data.instrumentationName + ": " + e.toString(), e);
3969 }
3970
3971 mInstrumentation.init(this, instrContext, appContext,
3972 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3973
3974 if (data.profileFile != null && !ii.handleProfiling) {
3975 data.handlingProfiling = true;
3976 File file = new File(data.profileFile);
3977 file.getParentFile().mkdirs();
3978 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3979 }
3980
3981 try {
3982 mInstrumentation.onCreate(data.instrumentationArgs);
3983 }
3984 catch (Exception e) {
3985 throw new RuntimeException(
3986 "Exception thrown in onCreate() of "
3987 + data.instrumentationName + ": " + e.toString(), e);
3988 }
3989
3990 } else {
3991 mInstrumentation = new Instrumentation();
3992 }
3993
Christopher Tate181fafa2009-05-14 11:12:14 -07003994 // If the app is being launched for full backup or restore, bring it up in
3995 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003996 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 mInitialApplication = app;
3998
3999 List<ProviderInfo> providers = data.providers;
4000 if (providers != null) {
4001 installContentProviders(app, providers);
4002 }
4003
4004 try {
4005 mInstrumentation.callApplicationOnCreate(app);
4006 } catch (Exception e) {
4007 if (!mInstrumentation.onException(app, e)) {
4008 throw new RuntimeException(
4009 "Unable to create application " + app.getClass().getName()
4010 + ": " + e.toString(), e);
4011 }
4012 }
4013 }
4014
4015 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
4016 IActivityManager am = ActivityManagerNative.getDefault();
4017 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
4018 Debug.stopMethodTracing();
4019 }
4020 //Log.i(TAG, "am: " + ActivityManagerNative.getDefault()
4021 // + ", app thr: " + mAppThread);
4022 try {
4023 am.finishInstrumentation(mAppThread, resultCode, results);
4024 } catch (RemoteException ex) {
4025 }
4026 }
4027
4028 private final void installContentProviders(
4029 Context context, List<ProviderInfo> providers) {
4030 final ArrayList<IActivityManager.ContentProviderHolder> results =
4031 new ArrayList<IActivityManager.ContentProviderHolder>();
4032
4033 Iterator<ProviderInfo> i = providers.iterator();
4034 while (i.hasNext()) {
4035 ProviderInfo cpi = i.next();
4036 StringBuilder buf = new StringBuilder(128);
4037 buf.append("Publishing provider ");
4038 buf.append(cpi.authority);
4039 buf.append(": ");
4040 buf.append(cpi.name);
4041 Log.i(TAG, buf.toString());
4042 IContentProvider cp = installProvider(context, null, cpi, false);
4043 if (cp != null) {
4044 IActivityManager.ContentProviderHolder cph =
4045 new IActivityManager.ContentProviderHolder(cpi);
4046 cph.provider = cp;
4047 results.add(cph);
4048 // Don't ever unload this provider from the process.
4049 synchronized(mProviderMap) {
4050 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
4051 }
4052 }
4053 }
4054
4055 try {
4056 ActivityManagerNative.getDefault().publishContentProviders(
4057 getApplicationThread(), results);
4058 } catch (RemoteException ex) {
4059 }
4060 }
4061
4062 private final IContentProvider getProvider(Context context, String name) {
4063 synchronized(mProviderMap) {
4064 final ProviderRecord pr = mProviderMap.get(name);
4065 if (pr != null) {
4066 return pr.mProvider;
4067 }
4068 }
4069
4070 IActivityManager.ContentProviderHolder holder = null;
4071 try {
4072 holder = ActivityManagerNative.getDefault().getContentProvider(
4073 getApplicationThread(), name);
4074 } catch (RemoteException ex) {
4075 }
4076 if (holder == null) {
4077 Log.e(TAG, "Failed to find provider info for " + name);
4078 return null;
4079 }
4080 if (holder.permissionFailure != null) {
4081 throw new SecurityException("Permission " + holder.permissionFailure
4082 + " required for provider " + name);
4083 }
4084
4085 IContentProvider prov = installProvider(context, holder.provider,
4086 holder.info, true);
4087 //Log.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
4088 if (holder.noReleaseNeeded || holder.provider == null) {
4089 // We are not going to release the provider if it is an external
4090 // provider that doesn't care about being released, or if it is
4091 // a local provider running in this process.
4092 //Log.i(TAG, "*** NO RELEASE NEEDED");
4093 synchronized(mProviderMap) {
4094 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
4095 }
4096 }
4097 return prov;
4098 }
4099
4100 public final IContentProvider acquireProvider(Context c, String name) {
4101 IContentProvider provider = getProvider(c, name);
4102 if(provider == null)
4103 return null;
4104 IBinder jBinder = provider.asBinder();
4105 synchronized(mProviderMap) {
4106 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4107 if(prc == null) {
4108 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4109 } else {
4110 prc.count++;
4111 } //end else
4112 } //end synchronized
4113 return provider;
4114 }
4115
4116 public final boolean releaseProvider(IContentProvider provider) {
4117 if(provider == null) {
4118 return false;
4119 }
4120 IBinder jBinder = provider.asBinder();
4121 synchronized(mProviderMap) {
4122 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4123 if(prc == null) {
4124 if(localLOGV) Log.v(TAG, "releaseProvider::Weird shouldnt be here");
4125 return false;
4126 } else {
4127 prc.count--;
4128 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004129 // Schedule the actual remove asynchronously, since we
4130 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004131 // TODO: it would be nice to post a delayed message, so
4132 // if we come back and need the same provider quickly
4133 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004134 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4135 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 } //end if
4137 } //end else
4138 } //end synchronized
4139 return true;
4140 }
4141
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004142 final void completeRemoveProvider(IContentProvider provider) {
4143 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004144 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004145 synchronized(mProviderMap) {
4146 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4147 if(prc != null && prc.count == 0) {
4148 mProviderRefCountMap.remove(jBinder);
4149 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004150 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004151 }
4152 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004153
4154 if (name != null) {
4155 try {
4156 if(localLOGV) Log.v(TAG, "removeProvider::Invoking " +
4157 "ActivityManagerNative.removeContentProvider(" + name);
4158 ActivityManagerNative.getDefault().removeContentProvider(
4159 getApplicationThread(), name);
4160 } catch (RemoteException e) {
4161 //do nothing content provider object is dead any way
4162 } //end catch
4163 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004164 }
4165
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004166 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004168 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004172 String name = null;
4173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 // remove the provider from mProviderMap
4175 Iterator<ProviderRecord> iter = mProviderMap.values().iterator();
4176 while (iter.hasNext()) {
4177 ProviderRecord pr = iter.next();
4178 IBinder myBinder = pr.mProvider.asBinder();
4179 if (myBinder == providerBinder) {
4180 //find if its published by this process itself
4181 if(pr.mLocalProvider != null) {
4182 if(localLOGV) Log.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004183 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 }
4185 if(localLOGV) Log.v(TAG, "removeProvider::Not local provider Unlinking " +
4186 "death recipient");
4187 //content provider is in another process
4188 myBinder.unlinkToDeath(pr, 0);
4189 iter.remove();
4190 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004191 if(name == null) {
4192 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 }
4194 } //end if myBinder
4195 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004196
4197 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 }
4199
4200 final void removeDeadProvider(String name, IContentProvider provider) {
4201 synchronized(mProviderMap) {
4202 ProviderRecord pr = mProviderMap.get(name);
4203 if (pr.mProvider.asBinder() == provider.asBinder()) {
4204 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004205 ProviderRecord removed = mProviderMap.remove(name);
4206 if (removed != null) {
4207 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 }
4210 }
4211 }
4212
4213 final void removeDeadProviderLocked(String name, IContentProvider provider) {
4214 ProviderRecord pr = mProviderMap.get(name);
4215 if (pr.mProvider.asBinder() == provider.asBinder()) {
4216 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004217 ProviderRecord removed = mProviderMap.remove(name);
4218 if (removed != null) {
4219 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 }
4222 }
4223
4224 private final IContentProvider installProvider(Context context,
4225 IContentProvider provider, ProviderInfo info, boolean noisy) {
4226 ContentProvider localProvider = null;
4227 if (provider == null) {
4228 if (noisy) {
4229 Log.d(TAG, "Loading provider " + info.authority + ": "
4230 + info.name);
4231 }
4232 Context c = null;
4233 ApplicationInfo ai = info.applicationInfo;
4234 if (context.getPackageName().equals(ai.packageName)) {
4235 c = context;
4236 } else if (mInitialApplication != null &&
4237 mInitialApplication.getPackageName().equals(ai.packageName)) {
4238 c = mInitialApplication;
4239 } else {
4240 try {
4241 c = context.createPackageContext(ai.packageName,
4242 Context.CONTEXT_INCLUDE_CODE);
4243 } catch (PackageManager.NameNotFoundException e) {
4244 }
4245 }
4246 if (c == null) {
4247 Log.w(TAG, "Unable to get context for package " +
4248 ai.packageName +
4249 " while loading content provider " +
4250 info.name);
4251 return null;
4252 }
4253 try {
4254 final java.lang.ClassLoader cl = c.getClassLoader();
4255 localProvider = (ContentProvider)cl.
4256 loadClass(info.name).newInstance();
4257 provider = localProvider.getIContentProvider();
4258 if (provider == null) {
4259 Log.e(TAG, "Failed to instantiate class " +
4260 info.name + " from sourceDir " +
4261 info.applicationInfo.sourceDir);
4262 return null;
4263 }
4264 if (Config.LOGV) Log.v(
4265 TAG, "Instantiating local provider " + info.name);
4266 // XXX Need to create the correct context for this provider.
4267 localProvider.attachInfo(c, info);
4268 } catch (java.lang.Exception e) {
4269 if (!mInstrumentation.onException(null, e)) {
4270 throw new RuntimeException(
4271 "Unable to get provider " + info.name
4272 + ": " + e.toString(), e);
4273 }
4274 return null;
4275 }
4276 } else if (localLOGV) {
4277 Log.v(TAG, "Installing external provider " + info.authority + ": "
4278 + info.name);
4279 }
4280
4281 synchronized (mProviderMap) {
4282 // Cache the pointer for the remote provider.
4283 String names[] = PATTERN_SEMICOLON.split(info.authority);
4284 for (int i=0; i<names.length; i++) {
4285 ProviderRecord pr = new ProviderRecord(names[i], provider,
4286 localProvider);
4287 try {
4288 provider.asBinder().linkToDeath(pr, 0);
4289 mProviderMap.put(names[i], pr);
4290 } catch (RemoteException e) {
4291 return null;
4292 }
4293 }
4294 if (localProvider != null) {
4295 mLocalProviders.put(provider.asBinder(),
4296 new ProviderRecord(null, provider, localProvider));
4297 }
4298 }
4299
4300 return provider;
4301 }
4302
4303 private final void attach(boolean system) {
4304 sThreadLocal.set(this);
4305 mSystemThread = system;
4306 AndroidHttpClient.setThreadBlocked(true);
4307 if (!system) {
4308 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4309 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4310 IActivityManager mgr = ActivityManagerNative.getDefault();
4311 try {
4312 mgr.attachApplication(mAppThread);
4313 } catch (RemoteException ex) {
4314 }
4315 } else {
4316 // Don't set application object here -- if the system crashes,
4317 // we can't display an alert, we just want to die die die.
4318 android.ddm.DdmHandleAppName.setAppName("system_process");
4319 try {
4320 mInstrumentation = new Instrumentation();
4321 ApplicationContext context = new ApplicationContext();
4322 context.init(getSystemContext().mPackageInfo, null, this);
4323 Application app = Instrumentation.newApplication(Application.class, context);
4324 mAllApplications.add(app);
4325 mInitialApplication = app;
4326 app.onCreate();
4327 } catch (Exception e) {
4328 throw new RuntimeException(
4329 "Unable to instantiate Application():" + e.toString(), e);
4330 }
4331 }
4332 }
4333
4334 private final void detach()
4335 {
4336 AndroidHttpClient.setThreadBlocked(false);
4337 sThreadLocal.set(null);
4338 }
4339
4340 public static final ActivityThread systemMain() {
4341 ActivityThread thread = new ActivityThread();
4342 thread.attach(true);
4343 return thread;
4344 }
4345
4346 public final void installSystemProviders(List providers) {
4347 if (providers != null) {
4348 installContentProviders(mInitialApplication,
4349 (List<ProviderInfo>)providers);
4350 }
4351 }
4352
4353 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004354 SamplingProfilerIntegration.start();
4355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 Process.setArgV0("<pre-initialized>");
4357
4358 Looper.prepareMainLooper();
4359
4360 ActivityThread thread = new ActivityThread();
4361 thread.attach(false);
4362
4363 Looper.loop();
4364
4365 if (Process.supportsProcesses()) {
4366 throw new RuntimeException("Main thread loop unexpectedly exited");
4367 }
4368
4369 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02004370 String name = (thread.mInitialApplication != null)
4371 ? thread.mInitialApplication.getPackageName()
4372 : "<unknown>";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 Log.i(TAG, "Main thread of " + name + " is now exiting");
4374 }
4375}