blob: daf4090369e2d2f768fefc3464860ce12b5a1457 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import android.content.BroadcastReceiver;
20import android.content.ComponentCallbacks;
21import android.content.ComponentName;
22import android.content.ContentProvider;
23import android.content.Context;
24import android.content.IContentProvider;
25import android.content.Intent;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070026import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.ServiceConnection;
28import android.content.pm.ActivityInfo;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.IPackageManager;
31import android.content.pm.InstrumentationInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.ProviderInfo;
34import android.content.pm.ServiceInfo;
35import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070036import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.database.sqlite.SQLiteDatabase;
40import android.database.sqlite.SQLiteDebug;
41import android.graphics.Bitmap;
42import android.graphics.Canvas;
43import android.net.http.AndroidHttpClient;
44import android.os.Bundle;
45import android.os.Debug;
46import android.os.Handler;
47import android.os.IBinder;
48import android.os.Looper;
49import android.os.Message;
50import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070051import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.Process;
53import android.os.RemoteException;
54import android.os.ServiceManager;
55import android.os.SystemClock;
56import android.util.AndroidRuntimeException;
57import android.util.Config;
58import android.util.DisplayMetrics;
59import android.util.EventLog;
60import android.util.Log;
61import android.view.Display;
62import android.view.View;
63import android.view.ViewDebug;
64import android.view.ViewManager;
65import android.view.Window;
66import android.view.WindowManager;
67import android.view.WindowManagerImpl;
68
69import com.android.internal.os.BinderInternal;
70import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070071import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import com.android.internal.util.ArrayUtils;
73
74import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
75
76import java.io.File;
77import java.io.FileDescriptor;
78import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070079import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import java.io.PrintWriter;
81import java.lang.ref.WeakReference;
82import java.util.ArrayList;
83import java.util.HashMap;
84import java.util.Iterator;
85import java.util.List;
86import java.util.Locale;
87import java.util.Map;
88import java.util.TimeZone;
89import java.util.regex.Pattern;
90
Bob Leee5408332009-09-04 18:31:17 -070091import dalvik.system.SamplingProfiler;
92
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093final class IntentReceiverLeaked extends AndroidRuntimeException {
94 public IntentReceiverLeaked(String msg) {
95 super(msg);
96 }
97}
98
99final class ServiceConnectionLeaked extends AndroidRuntimeException {
100 public ServiceConnectionLeaked(String msg) {
101 super(msg);
102 }
103}
104
105final class SuperNotCalledException extends AndroidRuntimeException {
106 public SuperNotCalledException(String msg) {
107 super(msg);
108 }
109}
110
111/**
112 * This manages the execution of the main thread in an
113 * application process, scheduling and executing activities,
114 * broadcasts, and other operations on it as the activity
115 * manager requests.
116 *
117 * {@hide}
118 */
119public final class ActivityThread {
120 private static final String TAG = "ActivityThread";
121 private static final boolean DEBUG = false;
122 private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
123 private static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700124 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700125 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700126 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
128 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
129 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
130 private static final int LOG_ON_PAUSE_CALLED = 30021;
131 private static final int LOG_ON_RESUME_CALLED = 30022;
132
Bob Leee5408332009-09-04 18:31:17 -0700133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 public static final ActivityThread currentActivityThread() {
135 return (ActivityThread)sThreadLocal.get();
136 }
137
138 public static final String currentPackageName()
139 {
140 ActivityThread am = currentActivityThread();
141 return (am != null && am.mBoundApplication != null)
142 ? am.mBoundApplication.processName : null;
143 }
144
145 public static IPackageManager getPackageManager() {
146 if (sPackageManager != null) {
147 //Log.v("PackageManager", "returning cur default = " + sPackageManager);
148 return sPackageManager;
149 }
150 IBinder b = ServiceManager.getService("package");
151 //Log.v("PackageManager", "default service binder = " + b);
152 sPackageManager = IPackageManager.Stub.asInterface(b);
153 //Log.v("PackageManager", "default service = " + sPackageManager);
154 return sPackageManager;
155 }
156
157 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
158 if (mDisplayMetrics != null && !forceUpdate) {
159 return mDisplayMetrics;
160 }
161 if (mDisplay == null) {
162 WindowManager wm = WindowManagerImpl.getDefault();
163 mDisplay = wm.getDefaultDisplay();
164 }
165 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
166 mDisplay.getMetrics(metrics);
167 //Log.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
168 // + metrics.heightPixels + " den=" + metrics.density
169 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
170 return metrics;
171 }
172
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700173 /**
174 * Creates the top level Resources for applications with the given compatibility info.
175 *
176 * @param resDir the resource directory.
177 * @param compInfo the compability info. It will use the default compatibility info when it's
178 * null.
179 */
180 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 synchronized (mPackages) {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700182 // Resources is app scale dependent.
183 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700184 if (false) {
185 Log.w(TAG, "getTopLevelResources: " + resDir + " / "
186 + compInfo.applicationScale);
187 }
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700188 WeakReference<Resources> wr = mActiveResources.get(key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 Resources r = wr != null ? wr.get() : null;
190 if (r != null && r.getAssets().isUpToDate()) {
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700191 if (false) {
192 Log.w(TAG, "Returning cached resources " + r + " " + resDir
193 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 return r;
196 }
197
198 //if (r != null) {
199 // Log.w(TAG, "Throwing away out-of-date resources!!!! "
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700200 // + r + " " + resDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 //}
202
203 AssetManager assets = new AssetManager();
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700204 if (assets.addAssetPath(resDir) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 return null;
206 }
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700207
208 //Log.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700209 DisplayMetrics metrics = getDisplayMetricsLocked(false);
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700210 r = new Resources(assets, metrics, getConfiguration(), compInfo);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700211 if (false) {
212 Log.i(TAG, "Created app resources " + resDir + " " + r + ": "
213 + r.getConfiguration() + " appScale="
214 + r.getCompatibilityInfo().applicationScale);
215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 // XXX need to remove entries when weak references go away
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700217 mActiveResources.put(key, new WeakReference<Resources>(r));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 return r;
219 }
220 }
221
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700222 /**
223 * Creates the top level resources for the given package.
224 */
225 Resources getTopLevelResources(String resDir, PackageInfo pkgInfo) {
226 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
227 }
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 final Handler getHandler() {
230 return mH;
231 }
232
233 public final static class PackageInfo {
234
235 private final ActivityThread mActivityThread;
236 private final ApplicationInfo mApplicationInfo;
237 private final String mPackageName;
238 private final String mAppDir;
239 private final String mResDir;
240 private final String[] mSharedLibraries;
241 private final String mDataDir;
242 private final File mDataDirFile;
243 private final ClassLoader mBaseClassLoader;
244 private final boolean mSecurityViolation;
245 private final boolean mIncludeCode;
246 private Resources mResources;
247 private ClassLoader mClassLoader;
248 private Application mApplication;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700249 private CompatibilityInfo mCompatibilityInfo;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mReceivers
252 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
253 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mUnregisteredReceivers
254 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
255 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mServices
256 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
257 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mUnboundServices
258 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
259
260 int mClientCount = 0;
261
262 public PackageInfo(ActivityThread activityThread, ApplicationInfo aInfo,
263 ActivityThread mainThread, ClassLoader baseLoader,
264 boolean securityViolation, boolean includeCode) {
265 mActivityThread = activityThread;
266 mApplicationInfo = aInfo;
267 mPackageName = aInfo.packageName;
268 mAppDir = aInfo.sourceDir;
269 mResDir = aInfo.uid == Process.myUid() ? aInfo.sourceDir
270 : aInfo.publicSourceDir;
271 mSharedLibraries = aInfo.sharedLibraryFiles;
272 mDataDir = aInfo.dataDir;
273 mDataDirFile = mDataDir != null ? new File(mDataDir) : null;
274 mBaseClassLoader = baseLoader;
275 mSecurityViolation = securityViolation;
276 mIncludeCode = includeCode;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700277 mCompatibilityInfo = new CompatibilityInfo(aInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278
279 if (mAppDir == null) {
280 if (mSystemContext == null) {
281 mSystemContext =
282 ApplicationContext.createSystemContext(mainThread);
283 mSystemContext.getResources().updateConfiguration(
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700284 mainThread.getConfiguration(),
285 mainThread.getDisplayMetricsLocked(false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 //Log.i(TAG, "Created system resources "
287 // + mSystemContext.getResources() + ": "
288 // + mSystemContext.getResources().getConfiguration());
289 }
290 mClassLoader = mSystemContext.getClassLoader();
291 mResources = mSystemContext.getResources();
292 }
293 }
294
295 public PackageInfo(ActivityThread activityThread, String name,
Mike Cleron432b7132009-09-24 15:28:29 -0700296 Context systemContext, ApplicationInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 mActivityThread = activityThread;
Mike Cleron432b7132009-09-24 15:28:29 -0700298 mApplicationInfo = info != null ? info : new ApplicationInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 mApplicationInfo.packageName = name;
300 mPackageName = name;
301 mAppDir = null;
302 mResDir = null;
303 mSharedLibraries = null;
304 mDataDir = null;
305 mDataDirFile = null;
306 mBaseClassLoader = null;
307 mSecurityViolation = false;
308 mIncludeCode = true;
309 mClassLoader = systemContext.getClassLoader();
310 mResources = systemContext.getResources();
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700311 mCompatibilityInfo = new CompatibilityInfo(mApplicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 }
313
314 public String getPackageName() {
315 return mPackageName;
316 }
317
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700318 public ApplicationInfo getApplicationInfo() {
319 return mApplicationInfo;
320 }
Bob Leee5408332009-09-04 18:31:17 -0700321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 public boolean isSecurityViolation() {
323 return mSecurityViolation;
324 }
325
326 /**
327 * Gets the array of shared libraries that are listed as
328 * used by the given package.
Bob Leee5408332009-09-04 18:31:17 -0700329 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 * @param packageName the name of the package (note: not its
331 * file name)
332 * @return null-ok; the array of shared libraries, each one
333 * a fully-qualified path
334 */
335 private static String[] getLibrariesFor(String packageName) {
336 ApplicationInfo ai = null;
337 try {
338 ai = getPackageManager().getApplicationInfo(packageName,
339 PackageManager.GET_SHARED_LIBRARY_FILES);
340 } catch (RemoteException e) {
341 throw new AssertionError(e);
342 }
343
344 if (ai == null) {
345 return null;
346 }
347
348 return ai.sharedLibraryFiles;
349 }
350
351 /**
352 * Combines two arrays (of library names) such that they are
353 * concatenated in order but are devoid of duplicates. The
354 * result is a single string with the names of the libraries
355 * separated by colons, or <code>null</code> if both lists
356 * were <code>null</code> or empty.
Bob Leee5408332009-09-04 18:31:17 -0700357 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 * @param list1 null-ok; the first list
359 * @param list2 null-ok; the second list
360 * @return null-ok; the combination
361 */
362 private static String combineLibs(String[] list1, String[] list2) {
363 StringBuilder result = new StringBuilder(300);
364 boolean first = true;
365
366 if (list1 != null) {
367 for (String s : list1) {
368 if (first) {
369 first = false;
370 } else {
371 result.append(':');
372 }
373 result.append(s);
374 }
375 }
376
377 // Only need to check for duplicates if list1 was non-empty.
378 boolean dupCheck = !first;
379
380 if (list2 != null) {
381 for (String s : list2) {
382 if (dupCheck && ArrayUtils.contains(list1, s)) {
383 continue;
384 }
Bob Leee5408332009-09-04 18:31:17 -0700385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 if (first) {
387 first = false;
388 } else {
389 result.append(':');
390 }
391 result.append(s);
392 }
393 }
394
395 return result.toString();
396 }
Bob Leee5408332009-09-04 18:31:17 -0700397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 public ClassLoader getClassLoader() {
399 synchronized (this) {
400 if (mClassLoader != null) {
401 return mClassLoader;
402 }
403
404 if (mIncludeCode && !mPackageName.equals("android")) {
405 String zip = mAppDir;
406
407 /*
408 * The following is a bit of a hack to inject
409 * instrumentation into the system: If the app
410 * being started matches one of the instrumentation names,
411 * then we combine both the "instrumentation" and
412 * "instrumented" app into the path, along with the
413 * concatenation of both apps' shared library lists.
414 */
415
416 String instrumentationAppDir =
417 mActivityThread.mInstrumentationAppDir;
418 String instrumentationAppPackage =
419 mActivityThread.mInstrumentationAppPackage;
420 String instrumentedAppDir =
421 mActivityThread.mInstrumentedAppDir;
422 String[] instrumentationLibs = null;
423
424 if (mAppDir.equals(instrumentationAppDir)
425 || mAppDir.equals(instrumentedAppDir)) {
426 zip = instrumentationAppDir + ":" + instrumentedAppDir;
427 if (! instrumentedAppDir.equals(instrumentationAppDir)) {
428 instrumentationLibs =
429 getLibrariesFor(instrumentationAppPackage);
430 }
431 }
432
433 if ((mSharedLibraries != null) ||
434 (instrumentationLibs != null)) {
Bob Leee5408332009-09-04 18:31:17 -0700435 zip =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 combineLibs(mSharedLibraries, instrumentationLibs)
437 + ':' + zip;
438 }
439
440 /*
441 * With all the combination done (if necessary, actually
442 * create the class loader.
443 */
444
445 if (localLOGV) Log.v(TAG, "Class path: " + zip);
446
447 mClassLoader =
448 ApplicationLoaders.getDefault().getClassLoader(
449 zip, mDataDir, mBaseClassLoader);
450 } else {
451 if (mBaseClassLoader == null) {
452 mClassLoader = ClassLoader.getSystemClassLoader();
453 } else {
454 mClassLoader = mBaseClassLoader;
455 }
456 }
457 return mClassLoader;
458 }
459 }
460
461 public String getAppDir() {
462 return mAppDir;
463 }
464
465 public String getResDir() {
466 return mResDir;
467 }
468
469 public String getDataDir() {
470 return mDataDir;
471 }
472
473 public File getDataDirFile() {
474 return mDataDirFile;
475 }
476
477 public AssetManager getAssets(ActivityThread mainThread) {
478 return getResources(mainThread).getAssets();
479 }
480
481 public Resources getResources(ActivityThread mainThread) {
482 if (mResources == null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700483 mResources = mainThread.getTopLevelResources(mResDir, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 }
485 return mResources;
486 }
487
Christopher Tate181fafa2009-05-14 11:12:14 -0700488 public Application makeApplication(boolean forceDefaultAppClass) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 if (mApplication != null) {
490 return mApplication;
491 }
Bob Leee5408332009-09-04 18:31:17 -0700492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 Application app = null;
Bob Leee5408332009-09-04 18:31:17 -0700494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 String appClass = mApplicationInfo.className;
Christopher Tate181fafa2009-05-14 11:12:14 -0700496 if (forceDefaultAppClass || (appClass == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 appClass = "android.app.Application";
498 }
499
500 try {
501 java.lang.ClassLoader cl = getClassLoader();
502 ApplicationContext appContext = new ApplicationContext();
503 appContext.init(this, null, mActivityThread);
504 app = mActivityThread.mInstrumentation.newApplication(
505 cl, appClass, appContext);
506 appContext.setOuterContext(app);
507 } catch (Exception e) {
508 if (!mActivityThread.mInstrumentation.onException(app, e)) {
509 throw new RuntimeException(
510 "Unable to instantiate application " + appClass
511 + ": " + e.toString(), e);
512 }
513 }
514 mActivityThread.mAllApplications.add(app);
515 return mApplication = app;
516 }
Bob Leee5408332009-09-04 18:31:17 -0700517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 public void removeContextRegistrations(Context context,
519 String who, String what) {
520 HashMap<BroadcastReceiver, ReceiverDispatcher> rmap =
521 mReceivers.remove(context);
522 if (rmap != null) {
523 Iterator<ReceiverDispatcher> it = rmap.values().iterator();
524 while (it.hasNext()) {
525 ReceiverDispatcher rd = it.next();
526 IntentReceiverLeaked leak = new IntentReceiverLeaked(
527 what + " " + who + " has leaked IntentReceiver "
528 + rd.getIntentReceiver() + " that was " +
529 "originally registered here. Are you missing a " +
530 "call to unregisterReceiver()?");
531 leak.setStackTrace(rd.getLocation().getStackTrace());
532 Log.e(TAG, leak.getMessage(), leak);
533 try {
534 ActivityManagerNative.getDefault().unregisterReceiver(
535 rd.getIIntentReceiver());
536 } catch (RemoteException e) {
537 // system crashed, nothing we can do
538 }
539 }
540 }
541 mUnregisteredReceivers.remove(context);
542 //Log.i(TAG, "Receiver registrations: " + mReceivers);
543 HashMap<ServiceConnection, ServiceDispatcher> smap =
544 mServices.remove(context);
545 if (smap != null) {
546 Iterator<ServiceDispatcher> it = smap.values().iterator();
547 while (it.hasNext()) {
548 ServiceDispatcher sd = it.next();
549 ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
550 what + " " + who + " has leaked ServiceConnection "
551 + sd.getServiceConnection() + " that was originally bound here");
552 leak.setStackTrace(sd.getLocation().getStackTrace());
553 Log.e(TAG, leak.getMessage(), leak);
554 try {
555 ActivityManagerNative.getDefault().unbindService(
556 sd.getIServiceConnection());
557 } catch (RemoteException e) {
558 // system crashed, nothing we can do
559 }
560 sd.doForget();
561 }
562 }
563 mUnboundServices.remove(context);
564 //Log.i(TAG, "Service registrations: " + mServices);
565 }
566
567 public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,
568 Context context, Handler handler,
569 Instrumentation instrumentation, boolean registered) {
570 synchronized (mReceivers) {
571 ReceiverDispatcher rd = null;
572 HashMap<BroadcastReceiver, ReceiverDispatcher> map = null;
573 if (registered) {
574 map = mReceivers.get(context);
575 if (map != null) {
576 rd = map.get(r);
577 }
578 }
579 if (rd == null) {
580 rd = new ReceiverDispatcher(r, context, handler,
581 instrumentation, registered);
582 if (registered) {
583 if (map == null) {
584 map = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
585 mReceivers.put(context, map);
586 }
587 map.put(r, rd);
588 }
589 } else {
590 rd.validate(context, handler);
591 }
592 return rd.getIIntentReceiver();
593 }
594 }
595
596 public IIntentReceiver forgetReceiverDispatcher(Context context,
597 BroadcastReceiver r) {
598 synchronized (mReceivers) {
599 HashMap<BroadcastReceiver, ReceiverDispatcher> map = mReceivers.get(context);
600 ReceiverDispatcher rd = null;
601 if (map != null) {
602 rd = map.get(r);
603 if (rd != null) {
604 map.remove(r);
605 if (map.size() == 0) {
606 mReceivers.remove(context);
607 }
608 if (r.getDebugUnregister()) {
609 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
610 = mUnregisteredReceivers.get(context);
611 if (holder == null) {
612 holder = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
613 mUnregisteredReceivers.put(context, holder);
614 }
615 RuntimeException ex = new IllegalArgumentException(
616 "Originally unregistered here:");
617 ex.fillInStackTrace();
618 rd.setUnregisterLocation(ex);
619 holder.put(r, rd);
620 }
621 return rd.getIIntentReceiver();
622 }
623 }
624 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
625 = mUnregisteredReceivers.get(context);
626 if (holder != null) {
627 rd = holder.get(r);
628 if (rd != null) {
629 RuntimeException ex = rd.getUnregisterLocation();
630 throw new IllegalArgumentException(
631 "Unregistering Receiver " + r
632 + " that was already unregistered", ex);
633 }
634 }
635 if (context == null) {
636 throw new IllegalStateException("Unbinding Receiver " + r
637 + " from Context that is no longer in use: " + context);
638 } else {
639 throw new IllegalArgumentException("Receiver not registered: " + r);
640 }
641
642 }
643 }
644
645 static final class ReceiverDispatcher {
646
647 final static class InnerReceiver extends IIntentReceiver.Stub {
648 final WeakReference<ReceiverDispatcher> mDispatcher;
649 final ReceiverDispatcher mStrongRef;
Bob Leee5408332009-09-04 18:31:17 -0700650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 InnerReceiver(ReceiverDispatcher rd, boolean strong) {
652 mDispatcher = new WeakReference<ReceiverDispatcher>(rd);
653 mStrongRef = strong ? rd : null;
654 }
655 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700656 String data, Bundle extras, boolean ordered, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 ReceiverDispatcher rd = mDispatcher.get();
658 if (DEBUG_BROADCAST) {
659 int seq = intent.getIntExtra("seq", -1);
660 Log.i(TAG, "Receiving broadcast " + intent.getAction() + " seq=" + seq
661 + " to " + rd);
662 }
663 if (rd != null) {
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700664 rd.performReceive(intent, resultCode, data, extras,
665 ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667 }
668 }
Bob Leee5408332009-09-04 18:31:17 -0700669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 final IIntentReceiver.Stub mIIntentReceiver;
671 final BroadcastReceiver mReceiver;
672 final Context mContext;
673 final Handler mActivityThread;
674 final Instrumentation mInstrumentation;
675 final boolean mRegistered;
676 final IntentReceiverLeaked mLocation;
677 RuntimeException mUnregisterLocation;
678
679 final class Args implements Runnable {
680 private Intent mCurIntent;
681 private int mCurCode;
682 private String mCurData;
683 private Bundle mCurMap;
684 private boolean mCurOrdered;
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700685 private boolean mCurSticky;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686
687 public void run() {
688 BroadcastReceiver receiver = mReceiver;
689 if (DEBUG_BROADCAST) {
690 int seq = mCurIntent.getIntExtra("seq", -1);
691 Log.i(TAG, "Dispathing broadcast " + mCurIntent.getAction() + " seq=" + seq
692 + " to " + mReceiver);
693 }
694 if (receiver == null) {
695 return;
696 }
697
698 IActivityManager mgr = ActivityManagerNative.getDefault();
699 Intent intent = mCurIntent;
700 mCurIntent = null;
701 try {
702 ClassLoader cl = mReceiver.getClass().getClassLoader();
703 intent.setExtrasClassLoader(cl);
704 if (mCurMap != null) {
705 mCurMap.setClassLoader(cl);
706 }
707 receiver.setOrderedHint(true);
708 receiver.setResult(mCurCode, mCurData, mCurMap);
709 receiver.clearAbortBroadcast();
710 receiver.setOrderedHint(mCurOrdered);
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700711 receiver.setInitialStickyHint(mCurSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 receiver.onReceive(mContext, intent);
713 } catch (Exception e) {
714 if (mRegistered && mCurOrdered) {
715 try {
716 mgr.finishReceiver(mIIntentReceiver,
717 mCurCode, mCurData, mCurMap, false);
718 } catch (RemoteException ex) {
719 }
720 }
721 if (mInstrumentation == null ||
722 !mInstrumentation.onException(mReceiver, e)) {
723 throw new RuntimeException(
724 "Error receiving broadcast " + intent
725 + " in " + mReceiver, e);
726 }
727 }
728 if (mRegistered && mCurOrdered) {
729 try {
730 mgr.finishReceiver(mIIntentReceiver,
731 receiver.getResultCode(),
732 receiver.getResultData(),
733 receiver.getResultExtras(false),
734 receiver.getAbortBroadcast());
735 } catch (RemoteException ex) {
736 }
737 }
738 }
739 }
740
741 ReceiverDispatcher(BroadcastReceiver receiver, Context context,
742 Handler activityThread, Instrumentation instrumentation,
743 boolean registered) {
744 if (activityThread == null) {
745 throw new NullPointerException("Handler must not be null");
746 }
747
748 mIIntentReceiver = new InnerReceiver(this, !registered);
749 mReceiver = receiver;
750 mContext = context;
751 mActivityThread = activityThread;
752 mInstrumentation = instrumentation;
753 mRegistered = registered;
754 mLocation = new IntentReceiverLeaked(null);
755 mLocation.fillInStackTrace();
756 }
757
758 void validate(Context context, Handler activityThread) {
759 if (mContext != context) {
760 throw new IllegalStateException(
761 "Receiver " + mReceiver +
762 " registered with differing Context (was " +
763 mContext + " now " + context + ")");
764 }
765 if (mActivityThread != activityThread) {
766 throw new IllegalStateException(
767 "Receiver " + mReceiver +
768 " registered with differing handler (was " +
769 mActivityThread + " now " + activityThread + ")");
770 }
771 }
772
773 IntentReceiverLeaked getLocation() {
774 return mLocation;
775 }
776
777 BroadcastReceiver getIntentReceiver() {
778 return mReceiver;
779 }
Bob Leee5408332009-09-04 18:31:17 -0700780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 IIntentReceiver getIIntentReceiver() {
782 return mIIntentReceiver;
783 }
784
785 void setUnregisterLocation(RuntimeException ex) {
786 mUnregisterLocation = ex;
787 }
788
789 RuntimeException getUnregisterLocation() {
790 return mUnregisterLocation;
791 }
792
793 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700794 String data, Bundle extras, boolean ordered, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 if (DEBUG_BROADCAST) {
796 int seq = intent.getIntExtra("seq", -1);
797 Log.i(TAG, "Enqueueing broadcast " + intent.getAction() + " seq=" + seq
798 + " to " + mReceiver);
799 }
800 Args args = new Args();
801 args.mCurIntent = intent;
802 args.mCurCode = resultCode;
803 args.mCurData = data;
804 args.mCurMap = extras;
805 args.mCurOrdered = ordered;
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700806 args.mCurSticky = sticky;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 if (!mActivityThread.post(args)) {
808 if (mRegistered) {
809 IActivityManager mgr = ActivityManagerNative.getDefault();
810 try {
811 mgr.finishReceiver(mIIntentReceiver, args.mCurCode,
812 args.mCurData, args.mCurMap, false);
813 } catch (RemoteException ex) {
814 }
815 }
816 }
817 }
818
819 }
820
821 public final IServiceConnection getServiceDispatcher(ServiceConnection c,
822 Context context, Handler handler, int flags) {
823 synchronized (mServices) {
824 ServiceDispatcher sd = null;
825 HashMap<ServiceConnection, ServiceDispatcher> map = mServices.get(context);
826 if (map != null) {
827 sd = map.get(c);
828 }
829 if (sd == null) {
830 sd = new ServiceDispatcher(c, context, handler, flags);
831 if (map == null) {
832 map = new HashMap<ServiceConnection, ServiceDispatcher>();
833 mServices.put(context, map);
834 }
835 map.put(c, sd);
836 } else {
837 sd.validate(context, handler);
838 }
839 return sd.getIServiceConnection();
840 }
841 }
842
843 public final IServiceConnection forgetServiceDispatcher(Context context,
844 ServiceConnection c) {
845 synchronized (mServices) {
846 HashMap<ServiceConnection, ServiceDispatcher> map
847 = mServices.get(context);
848 ServiceDispatcher sd = null;
849 if (map != null) {
850 sd = map.get(c);
851 if (sd != null) {
852 map.remove(c);
853 sd.doForget();
854 if (map.size() == 0) {
855 mServices.remove(context);
856 }
857 if ((sd.getFlags()&Context.BIND_DEBUG_UNBIND) != 0) {
858 HashMap<ServiceConnection, ServiceDispatcher> holder
859 = mUnboundServices.get(context);
860 if (holder == null) {
861 holder = new HashMap<ServiceConnection, ServiceDispatcher>();
862 mUnboundServices.put(context, holder);
863 }
864 RuntimeException ex = new IllegalArgumentException(
865 "Originally unbound here:");
866 ex.fillInStackTrace();
867 sd.setUnbindLocation(ex);
868 holder.put(c, sd);
869 }
870 return sd.getIServiceConnection();
871 }
872 }
873 HashMap<ServiceConnection, ServiceDispatcher> holder
874 = mUnboundServices.get(context);
875 if (holder != null) {
876 sd = holder.get(c);
877 if (sd != null) {
878 RuntimeException ex = sd.getUnbindLocation();
879 throw new IllegalArgumentException(
880 "Unbinding Service " + c
881 + " that was already unbound", ex);
882 }
883 }
884 if (context == null) {
885 throw new IllegalStateException("Unbinding Service " + c
886 + " from Context that is no longer in use: " + context);
887 } else {
888 throw new IllegalArgumentException("Service not registered: " + c);
889 }
890 }
891 }
892
893 static final class ServiceDispatcher {
894 private final InnerConnection mIServiceConnection;
895 private final ServiceConnection mConnection;
896 private final Context mContext;
897 private final Handler mActivityThread;
898 private final ServiceConnectionLeaked mLocation;
899 private final int mFlags;
900
901 private RuntimeException mUnbindLocation;
902
903 private boolean mDied;
904
905 private static class ConnectionInfo {
906 IBinder binder;
907 IBinder.DeathRecipient deathMonitor;
908 }
909
910 private static class InnerConnection extends IServiceConnection.Stub {
911 final WeakReference<ServiceDispatcher> mDispatcher;
Bob Leee5408332009-09-04 18:31:17 -0700912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 InnerConnection(ServiceDispatcher sd) {
914 mDispatcher = new WeakReference<ServiceDispatcher>(sd);
915 }
916
917 public void connected(ComponentName name, IBinder service) throws RemoteException {
918 ServiceDispatcher sd = mDispatcher.get();
919 if (sd != null) {
920 sd.connected(name, service);
921 }
922 }
923 }
Bob Leee5408332009-09-04 18:31:17 -0700924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 private final HashMap<ComponentName, ConnectionInfo> mActiveConnections
926 = new HashMap<ComponentName, ConnectionInfo>();
927
928 ServiceDispatcher(ServiceConnection conn,
929 Context context, Handler activityThread, int flags) {
930 mIServiceConnection = new InnerConnection(this);
931 mConnection = conn;
932 mContext = context;
933 mActivityThread = activityThread;
934 mLocation = new ServiceConnectionLeaked(null);
935 mLocation.fillInStackTrace();
936 mFlags = flags;
937 }
938
939 void validate(Context context, Handler activityThread) {
940 if (mContext != context) {
941 throw new RuntimeException(
942 "ServiceConnection " + mConnection +
943 " registered with differing Context (was " +
944 mContext + " now " + context + ")");
945 }
946 if (mActivityThread != activityThread) {
947 throw new RuntimeException(
948 "ServiceConnection " + mConnection +
949 " registered with differing handler (was " +
950 mActivityThread + " now " + activityThread + ")");
951 }
952 }
953
954 void doForget() {
955 synchronized(this) {
956 Iterator<ConnectionInfo> it = mActiveConnections.values().iterator();
957 while (it.hasNext()) {
958 ConnectionInfo ci = it.next();
959 ci.binder.unlinkToDeath(ci.deathMonitor, 0);
960 }
961 mActiveConnections.clear();
962 }
963 }
964
965 ServiceConnectionLeaked getLocation() {
966 return mLocation;
967 }
968
969 ServiceConnection getServiceConnection() {
970 return mConnection;
971 }
972
973 IServiceConnection getIServiceConnection() {
974 return mIServiceConnection;
975 }
Bob Leee5408332009-09-04 18:31:17 -0700976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 int getFlags() {
978 return mFlags;
979 }
980
981 void setUnbindLocation(RuntimeException ex) {
982 mUnbindLocation = ex;
983 }
984
985 RuntimeException getUnbindLocation() {
986 return mUnbindLocation;
987 }
988
989 public void connected(ComponentName name, IBinder service) {
990 if (mActivityThread != null) {
991 mActivityThread.post(new RunConnection(name, service, 0));
992 } else {
993 doConnected(name, service);
994 }
995 }
996
997 public void death(ComponentName name, IBinder service) {
998 ConnectionInfo old;
999
1000 synchronized (this) {
1001 mDied = true;
1002 old = mActiveConnections.remove(name);
1003 if (old == null || old.binder != service) {
1004 // Death for someone different than who we last
1005 // reported... just ignore it.
1006 return;
1007 }
1008 old.binder.unlinkToDeath(old.deathMonitor, 0);
1009 }
1010
1011 if (mActivityThread != null) {
1012 mActivityThread.post(new RunConnection(name, service, 1));
1013 } else {
1014 doDeath(name, service);
1015 }
1016 }
1017
1018 public void doConnected(ComponentName name, IBinder service) {
1019 ConnectionInfo old;
1020 ConnectionInfo info;
1021
1022 synchronized (this) {
1023 old = mActiveConnections.get(name);
1024 if (old != null && old.binder == service) {
1025 // Huh, already have this one. Oh well!
1026 return;
1027 }
1028
1029 if (service != null) {
1030 // A new service is being connected... set it all up.
1031 mDied = false;
1032 info = new ConnectionInfo();
1033 info.binder = service;
1034 info.deathMonitor = new DeathMonitor(name, service);
1035 try {
1036 service.linkToDeath(info.deathMonitor, 0);
1037 mActiveConnections.put(name, info);
1038 } catch (RemoteException e) {
1039 // This service was dead before we got it... just
1040 // don't do anything with it.
1041 mActiveConnections.remove(name);
1042 return;
1043 }
1044
1045 } else {
1046 // The named service is being disconnected... clean up.
1047 mActiveConnections.remove(name);
1048 }
1049
1050 if (old != null) {
1051 old.binder.unlinkToDeath(old.deathMonitor, 0);
1052 }
1053 }
1054
1055 // If there was an old service, it is not disconnected.
1056 if (old != null) {
1057 mConnection.onServiceDisconnected(name);
1058 }
1059 // If there is a new service, it is now connected.
1060 if (service != null) {
1061 mConnection.onServiceConnected(name, service);
1062 }
1063 }
1064
1065 public void doDeath(ComponentName name, IBinder service) {
1066 mConnection.onServiceDisconnected(name);
1067 }
1068
1069 private final class RunConnection implements Runnable {
1070 RunConnection(ComponentName name, IBinder service, int command) {
1071 mName = name;
1072 mService = service;
1073 mCommand = command;
1074 }
1075
1076 public void run() {
1077 if (mCommand == 0) {
1078 doConnected(mName, mService);
1079 } else if (mCommand == 1) {
1080 doDeath(mName, mService);
1081 }
1082 }
1083
1084 final ComponentName mName;
1085 final IBinder mService;
1086 final int mCommand;
1087 }
1088
1089 private final class DeathMonitor implements IBinder.DeathRecipient
1090 {
1091 DeathMonitor(ComponentName name, IBinder service) {
1092 mName = name;
1093 mService = service;
1094 }
1095
1096 public void binderDied() {
1097 death(mName, mService);
1098 }
1099
1100 final ComponentName mName;
1101 final IBinder mService;
1102 }
1103 }
1104 }
1105
1106 private static ApplicationContext mSystemContext = null;
1107
1108 private static final class ActivityRecord {
1109 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001110 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 Intent intent;
1112 Bundle state;
1113 Activity activity;
1114 Window window;
1115 Activity parent;
1116 String embeddedID;
1117 Object lastNonConfigurationInstance;
1118 HashMap<String,Object> lastNonConfigurationChildInstances;
1119 boolean paused;
1120 boolean stopped;
1121 boolean hideForNow;
1122 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -07001123 Configuration createdConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 ActivityRecord nextIdle;
1125
1126 ActivityInfo activityInfo;
1127 PackageInfo packageInfo;
1128
1129 List<ResultInfo> pendingResults;
1130 List<Intent> pendingIntents;
1131
1132 boolean startsNotResumed;
1133 boolean isForward;
1134
1135 ActivityRecord() {
1136 parent = null;
1137 embeddedID = null;
1138 paused = false;
1139 stopped = false;
1140 hideForNow = false;
1141 nextIdle = null;
1142 }
1143
1144 public String toString() {
1145 ComponentName componentName = intent.getComponent();
1146 return "ActivityRecord{"
1147 + Integer.toHexString(System.identityHashCode(this))
1148 + " token=" + token + " " + (componentName == null
1149 ? "no component name" : componentName.toShortString())
1150 + "}";
1151 }
1152 }
1153
1154 private final class ProviderRecord implements IBinder.DeathRecipient {
1155 final String mName;
1156 final IContentProvider mProvider;
1157 final ContentProvider mLocalProvider;
1158
1159 ProviderRecord(String name, IContentProvider provider,
1160 ContentProvider localProvider) {
1161 mName = name;
1162 mProvider = provider;
1163 mLocalProvider = localProvider;
1164 }
1165
1166 public void binderDied() {
1167 removeDeadProvider(mName, mProvider);
1168 }
1169 }
1170
1171 private static final class NewIntentData {
1172 List<Intent> intents;
1173 IBinder token;
1174 public String toString() {
1175 return "NewIntentData{intents=" + intents + " token=" + token + "}";
1176 }
1177 }
1178
1179 private static final class ReceiverData {
1180 Intent intent;
1181 ActivityInfo info;
1182 int resultCode;
1183 String resultData;
1184 Bundle resultExtras;
1185 boolean sync;
1186 boolean resultAbort;
1187 public String toString() {
1188 return "ReceiverData{intent=" + intent + " packageName=" +
1189 info.packageName + " resultCode=" + resultCode
1190 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
1191 }
1192 }
1193
Christopher Tate181fafa2009-05-14 11:12:14 -07001194 private static final class CreateBackupAgentData {
1195 ApplicationInfo appInfo;
1196 int backupMode;
1197 public String toString() {
1198 return "CreateBackupAgentData{appInfo=" + appInfo
1199 + " backupAgent=" + appInfo.backupAgentName
1200 + " mode=" + backupMode + "}";
1201 }
1202 }
Bob Leee5408332009-09-04 18:31:17 -07001203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 private static final class CreateServiceData {
1205 IBinder token;
1206 ServiceInfo info;
1207 Intent intent;
1208 public String toString() {
1209 return "CreateServiceData{token=" + token + " className="
1210 + info.name + " packageName=" + info.packageName
1211 + " intent=" + intent + "}";
1212 }
1213 }
1214
1215 private static final class BindServiceData {
1216 IBinder token;
1217 Intent intent;
1218 boolean rebind;
1219 public String toString() {
1220 return "BindServiceData{token=" + token + " intent=" + intent + "}";
1221 }
1222 }
1223
1224 private static final class ServiceArgsData {
1225 IBinder token;
1226 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001227 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 Intent args;
1229 public String toString() {
1230 return "ServiceArgsData{token=" + token + " startId=" + startId
1231 + " args=" + args + "}";
1232 }
1233 }
1234
1235 private static final class AppBindData {
1236 PackageInfo info;
1237 String processName;
1238 ApplicationInfo appInfo;
1239 List<ProviderInfo> providers;
1240 ComponentName instrumentationName;
1241 String profileFile;
1242 Bundle instrumentationArgs;
1243 IInstrumentationWatcher instrumentationWatcher;
1244 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001245 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 Configuration config;
1247 boolean handlingProfiling;
1248 public String toString() {
1249 return "AppBindData{appInfo=" + appInfo + "}";
1250 }
1251 }
1252
1253 private static final class DumpServiceInfo {
1254 FileDescriptor fd;
1255 IBinder service;
1256 String[] args;
1257 boolean dumped;
1258 }
1259
1260 private static final class ResultData {
1261 IBinder token;
1262 List<ResultInfo> results;
1263 public String toString() {
1264 return "ResultData{token=" + token + " results" + results + "}";
1265 }
1266 }
1267
1268 private static final class ContextCleanupInfo {
1269 ApplicationContext context;
1270 String what;
1271 String who;
1272 }
1273
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001274 private static final class ProfilerControlData {
1275 String path;
1276 ParcelFileDescriptor fd;
1277 }
1278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 private final class ApplicationThread extends ApplicationThreadNative {
1280 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
1281 private static final String ONE_COUNT_COLUMN = "%17s %8d";
1282 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Bob Leee5408332009-09-04 18:31:17 -07001283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 // Formatting for checkin service - update version if row format changes
1285 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -07001286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 public final void schedulePauseActivity(IBinder token, boolean finished,
1288 boolean userLeaving, int configChanges) {
1289 queueOrSendMessage(
1290 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
1291 token,
1292 (userLeaving ? 1 : 0),
1293 configChanges);
1294 }
1295
1296 public final void scheduleStopActivity(IBinder token, boolean showWindow,
1297 int configChanges) {
1298 queueOrSendMessage(
1299 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
1300 token, 0, configChanges);
1301 }
1302
1303 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
1304 queueOrSendMessage(
1305 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
1306 token);
1307 }
1308
1309 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
1310 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
1311 }
1312
1313 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
1314 ResultData res = new ResultData();
1315 res.token = token;
1316 res.results = results;
1317 queueOrSendMessage(H.SEND_RESULT, res);
1318 }
1319
1320 // we use token to identify this activity without having to send the
1321 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001322 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
1324 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
1325 ActivityRecord r = new ActivityRecord();
1326
1327 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001328 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 r.intent = intent;
1330 r.activityInfo = info;
1331 r.state = state;
1332
1333 r.pendingResults = pendingResults;
1334 r.pendingIntents = pendingNewIntents;
1335
1336 r.startsNotResumed = notResumed;
1337 r.isForward = isForward;
1338
1339 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
1340 }
1341
1342 public final void scheduleRelaunchActivity(IBinder token,
1343 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
1344 int configChanges, boolean notResumed) {
1345 ActivityRecord r = new ActivityRecord();
1346
1347 r.token = token;
1348 r.pendingResults = pendingResults;
1349 r.pendingIntents = pendingNewIntents;
1350 r.startsNotResumed = notResumed;
1351
1352 synchronized (mRelaunchingActivities) {
1353 mRelaunchingActivities.add(r);
1354 }
Bob Leee5408332009-09-04 18:31:17 -07001355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
1357 }
1358
1359 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
1360 NewIntentData data = new NewIntentData();
1361 data.intents = intents;
1362 data.token = token;
1363
1364 queueOrSendMessage(H.NEW_INTENT, data);
1365 }
1366
1367 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
1368 int configChanges) {
1369 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
1370 configChanges);
1371 }
1372
1373 public final void scheduleReceiver(Intent intent, ActivityInfo info,
1374 int resultCode, String data, Bundle extras, boolean sync) {
1375 ReceiverData r = new ReceiverData();
1376
1377 r.intent = intent;
1378 r.info = info;
1379 r.resultCode = resultCode;
1380 r.resultData = data;
1381 r.resultExtras = extras;
1382 r.sync = sync;
1383
1384 queueOrSendMessage(H.RECEIVER, r);
1385 }
1386
Christopher Tate181fafa2009-05-14 11:12:14 -07001387 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
1388 CreateBackupAgentData d = new CreateBackupAgentData();
1389 d.appInfo = app;
1390 d.backupMode = backupMode;
1391
1392 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
1393 }
1394
1395 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
1396 CreateBackupAgentData d = new CreateBackupAgentData();
1397 d.appInfo = app;
1398
1399 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
1400 }
1401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 public final void scheduleCreateService(IBinder token,
1403 ServiceInfo info) {
1404 CreateServiceData s = new CreateServiceData();
1405 s.token = token;
1406 s.info = info;
1407
1408 queueOrSendMessage(H.CREATE_SERVICE, s);
1409 }
1410
1411 public final void scheduleBindService(IBinder token, Intent intent,
1412 boolean rebind) {
1413 BindServiceData s = new BindServiceData();
1414 s.token = token;
1415 s.intent = intent;
1416 s.rebind = rebind;
1417
1418 queueOrSendMessage(H.BIND_SERVICE, s);
1419 }
1420
1421 public final void scheduleUnbindService(IBinder token, Intent intent) {
1422 BindServiceData s = new BindServiceData();
1423 s.token = token;
1424 s.intent = intent;
1425
1426 queueOrSendMessage(H.UNBIND_SERVICE, s);
1427 }
1428
1429 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001430 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 ServiceArgsData s = new ServiceArgsData();
1432 s.token = token;
1433 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001434 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 s.args = args;
1436
1437 queueOrSendMessage(H.SERVICE_ARGS, s);
1438 }
1439
1440 public final void scheduleStopService(IBinder token) {
1441 queueOrSendMessage(H.STOP_SERVICE, token);
1442 }
1443
1444 public final void bindApplication(String processName,
1445 ApplicationInfo appInfo, List<ProviderInfo> providers,
1446 ComponentName instrumentationName, String profileFile,
1447 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -07001448 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450
1451 if (services != null) {
1452 // Setup the service cache in the ServiceManager
1453 ServiceManager.initServiceCache(services);
1454 }
1455
1456 AppBindData data = new AppBindData();
1457 data.processName = processName;
1458 data.appInfo = appInfo;
1459 data.providers = providers;
1460 data.instrumentationName = instrumentationName;
1461 data.profileFile = profileFile;
1462 data.instrumentationArgs = instrumentationArgs;
1463 data.instrumentationWatcher = instrumentationWatcher;
1464 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001465 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 data.config = config;
1467 queueOrSendMessage(H.BIND_APPLICATION, data);
1468 }
1469
1470 public final void scheduleExit() {
1471 queueOrSendMessage(H.EXIT_APPLICATION, null);
1472 }
1473
Christopher Tate5e1ab332009-09-01 20:32:49 -07001474 public final void scheduleSuicide() {
1475 queueOrSendMessage(H.SUICIDE, null);
1476 }
1477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 public void requestThumbnail(IBinder token) {
1479 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
1480 }
1481
1482 public void scheduleConfigurationChanged(Configuration config) {
1483 synchronized (mRelaunchingActivities) {
1484 mPendingConfiguration = config;
1485 }
1486 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
1487 }
1488
1489 public void updateTimeZone() {
1490 TimeZone.setDefault(null);
1491 }
1492
1493 public void processInBackground() {
1494 mH.removeMessages(H.GC_WHEN_IDLE);
1495 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1496 }
1497
1498 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
1499 DumpServiceInfo data = new DumpServiceInfo();
1500 data.fd = fd;
1501 data.service = servicetoken;
1502 data.args = args;
1503 data.dumped = false;
1504 queueOrSendMessage(H.DUMP_SERVICE, data);
1505 synchronized (data) {
1506 while (!data.dumped) {
1507 try {
1508 data.wait();
1509 } catch (InterruptedException e) {
1510 // no need to do anything here, we will keep waiting until
1511 // dumped is set
1512 }
1513 }
1514 }
1515 }
1516
1517 // This function exists to make sure all receiver dispatching is
1518 // correctly ordered, since these are one-way calls and the binder driver
1519 // applies transaction ordering per object for such calls.
1520 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001521 int resultCode, String dataStr, Bundle extras, boolean ordered,
1522 boolean sticky) throws RemoteException {
1523 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 }
Bob Leee5408332009-09-04 18:31:17 -07001525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 public void scheduleLowMemory() {
1527 queueOrSendMessage(H.LOW_MEMORY, null);
1528 }
1529
1530 public void scheduleActivityConfigurationChanged(IBinder token) {
1531 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
1532 }
1533
1534 public void requestPss() {
1535 try {
1536 ActivityManagerNative.getDefault().reportPss(this,
1537 (int)Process.getPss(Process.myPid()));
1538 } catch (RemoteException e) {
1539 }
1540 }
Bob Leee5408332009-09-04 18:31:17 -07001541
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001542 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
1543 ProfilerControlData pcd = new ProfilerControlData();
1544 pcd.path = path;
1545 pcd.fd = fd;
1546 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001547 }
1548
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001549 public void setSchedulingGroup(int group) {
1550 // Note: do this immediately, since going into the foreground
1551 // should happen regardless of what pending work we have to do
1552 // and the activity manager will wait for us to report back that
1553 // we are done before sending us to the background.
1554 try {
1555 Process.setProcessGroup(Process.myPid(), group);
1556 } catch (Exception e) {
1557 Log.w(TAG, "Failed setting process group to " + group, e);
1558 }
1559 }
Bob Leee5408332009-09-04 18:31:17 -07001560
Dianne Hackborn3025ef32009-08-31 21:31:47 -07001561 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
1562 Debug.getMemoryInfo(outInfo);
1563 }
Bob Leee5408332009-09-04 18:31:17 -07001564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 @Override
1566 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1567 long nativeMax = Debug.getNativeHeapSize() / 1024;
1568 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1569 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1570
1571 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
1572 Debug.getMemoryInfo(memInfo);
1573
1574 final int nativeShared = memInfo.nativeSharedDirty;
1575 final int dalvikShared = memInfo.dalvikSharedDirty;
1576 final int otherShared = memInfo.otherSharedDirty;
1577
1578 final int nativePrivate = memInfo.nativePrivateDirty;
1579 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
1580 final int otherPrivate = memInfo.otherPrivateDirty;
1581
1582 Runtime runtime = Runtime.getRuntime();
1583
1584 long dalvikMax = runtime.totalMemory() / 1024;
1585 long dalvikFree = runtime.freeMemory() / 1024;
1586 long dalvikAllocated = dalvikMax - dalvikFree;
1587 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1588 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
1589 long appContextInstanceCount = ApplicationContext.getInstanceCount();
1590 long activityInstanceCount = Activity.getInstanceCount();
1591 int globalAssetCount = AssetManager.getGlobalAssetCount();
1592 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1593 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1594 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1595 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1596 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
1597 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
1598 SQLiteDebug.PagerStats stats = new SQLiteDebug.PagerStats();
1599 SQLiteDebug.getPagerStats(stats);
Bob Leee5408332009-09-04 18:31:17 -07001600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 // Check to see if we were called by checkin server. If so, print terse format.
1602 boolean doCheckinFormat = false;
1603 if (args != null) {
1604 for (String arg : args) {
1605 if ("-c".equals(arg)) doCheckinFormat = true;
1606 }
1607 }
Bob Leee5408332009-09-04 18:31:17 -07001608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 // For checkin, we print one long comma-separated list of values
1610 if (doCheckinFormat) {
1611 // NOTE: if you change anything significant below, also consider changing
1612 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -07001613 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -07001615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 // Header
1617 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
1618 pw.print(Process.myPid()); pw.print(',');
1619 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 // Heap info - max
1622 pw.print(nativeMax); pw.print(',');
1623 pw.print(dalvikMax); pw.print(',');
1624 pw.print("N/A,");
1625 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 // Heap info - allocated
1628 pw.print(nativeAllocated); pw.print(',');
1629 pw.print(dalvikAllocated); pw.print(',');
1630 pw.print("N/A,");
1631 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 // Heap info - free
1634 pw.print(nativeFree); pw.print(',');
1635 pw.print(dalvikFree); pw.print(',');
1636 pw.print("N/A,");
1637 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 // Heap info - proportional set size
1640 pw.print(memInfo.nativePss); pw.print(',');
1641 pw.print(memInfo.dalvikPss); pw.print(',');
1642 pw.print(memInfo.otherPss); pw.print(',');
1643 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -07001646 pw.print(nativeShared); pw.print(',');
1647 pw.print(dalvikShared); pw.print(',');
1648 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -07001652 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 pw.print(dalvikPrivate); pw.print(',');
1654 pw.print(otherPrivate); pw.print(',');
1655 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 // Object counts
1658 pw.print(viewInstanceCount); pw.print(',');
1659 pw.print(viewRootInstanceCount); pw.print(',');
1660 pw.print(appContextInstanceCount); pw.print(',');
1661 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 pw.print(globalAssetCount); pw.print(',');
1664 pw.print(globalAssetManagerCount); pw.print(',');
1665 pw.print(binderLocalObjectCount); pw.print(',');
1666 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 pw.print(binderDeathObjectCount); pw.print(',');
1669 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 // SQL
1672 pw.print(sqliteAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001673 pw.print(stats.databaseBytes / 1024); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 pw.print(stats.numPagers); pw.print(',');
1675 pw.print((stats.totalBytes - stats.referencedBytes) / 1024); pw.print(',');
1676 pw.print(stats.referencedBytes / 1024); pw.print('\n');
Bob Leee5408332009-09-04 18:31:17 -07001677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 return;
1679 }
Bob Leee5408332009-09-04 18:31:17 -07001680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 // otherwise, show human-readable format
1682 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
1683 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
1684 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
1685 nativeAllocated + dalvikAllocated);
1686 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
1687 nativeFree + dalvikFree);
1688
1689 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
1690 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
1691
1692 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
1693 nativeShared + dalvikShared + otherShared);
1694 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
1695 nativePrivate + dalvikPrivate + otherPrivate);
1696
1697 pw.println(" ");
1698 pw.println(" Objects");
1699 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
1700 viewRootInstanceCount);
1701
1702 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1703 "Activities:", activityInstanceCount);
1704
1705 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1706 "AssetManagers:", globalAssetManagerCount);
1707
1708 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1709 "Proxy Binders:", binderProxyObjectCount);
1710 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1711
1712 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 // SQLite mem info
1715 pw.println(" ");
1716 pw.println(" SQL");
1717 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "dbFiles:",
1718 stats.databaseBytes / 1024);
1719 printRow(pw, TWO_COUNT_COLUMNS, "numPagers:", stats.numPagers, "inactivePageKB:",
1720 (stats.totalBytes - stats.referencedBytes) / 1024);
1721 printRow(pw, ONE_COUNT_COLUMN, "activePageKB:", stats.referencedBytes / 1024);
Bob Leee5408332009-09-04 18:31:17 -07001722
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001723 // Asset details.
1724 String assetAlloc = AssetManager.getAssetAllocations();
1725 if (assetAlloc != null) {
1726 pw.println(" ");
1727 pw.println(" Asset Allocations");
1728 pw.print(assetAlloc);
1729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 }
1731
1732 private void printRow(PrintWriter pw, String format, Object...objs) {
1733 pw.println(String.format(format, objs));
1734 }
1735 }
1736
1737 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -07001738 private H() {
1739 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
1740 }
1741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 public static final int LAUNCH_ACTIVITY = 100;
1743 public static final int PAUSE_ACTIVITY = 101;
1744 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1745 public static final int STOP_ACTIVITY_SHOW = 103;
1746 public static final int STOP_ACTIVITY_HIDE = 104;
1747 public static final int SHOW_WINDOW = 105;
1748 public static final int HIDE_WINDOW = 106;
1749 public static final int RESUME_ACTIVITY = 107;
1750 public static final int SEND_RESULT = 108;
1751 public static final int DESTROY_ACTIVITY = 109;
1752 public static final int BIND_APPLICATION = 110;
1753 public static final int EXIT_APPLICATION = 111;
1754 public static final int NEW_INTENT = 112;
1755 public static final int RECEIVER = 113;
1756 public static final int CREATE_SERVICE = 114;
1757 public static final int SERVICE_ARGS = 115;
1758 public static final int STOP_SERVICE = 116;
1759 public static final int REQUEST_THUMBNAIL = 117;
1760 public static final int CONFIGURATION_CHANGED = 118;
1761 public static final int CLEAN_UP_CONTEXT = 119;
1762 public static final int GC_WHEN_IDLE = 120;
1763 public static final int BIND_SERVICE = 121;
1764 public static final int UNBIND_SERVICE = 122;
1765 public static final int DUMP_SERVICE = 123;
1766 public static final int LOW_MEMORY = 124;
1767 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1768 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001769 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001770 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001771 public static final int DESTROY_BACKUP_AGENT = 129;
1772 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001773 public static final int REMOVE_PROVIDER = 131;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 String codeToString(int code) {
1775 if (localLOGV) {
1776 switch (code) {
1777 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1778 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1779 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1780 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1781 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1782 case SHOW_WINDOW: return "SHOW_WINDOW";
1783 case HIDE_WINDOW: return "HIDE_WINDOW";
1784 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1785 case SEND_RESULT: return "SEND_RESULT";
1786 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1787 case BIND_APPLICATION: return "BIND_APPLICATION";
1788 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1789 case NEW_INTENT: return "NEW_INTENT";
1790 case RECEIVER: return "RECEIVER";
1791 case CREATE_SERVICE: return "CREATE_SERVICE";
1792 case SERVICE_ARGS: return "SERVICE_ARGS";
1793 case STOP_SERVICE: return "STOP_SERVICE";
1794 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1795 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1796 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1797 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1798 case BIND_SERVICE: return "BIND_SERVICE";
1799 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1800 case DUMP_SERVICE: return "DUMP_SERVICE";
1801 case LOW_MEMORY: return "LOW_MEMORY";
1802 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1803 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001804 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001805 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1806 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001807 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001808 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
1811 return "(unknown)";
1812 }
1813 public void handleMessage(Message msg) {
1814 switch (msg.what) {
1815 case LAUNCH_ACTIVITY: {
1816 ActivityRecord r = (ActivityRecord)msg.obj;
1817
1818 r.packageInfo = getPackageInfoNoCheck(
1819 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001820 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 } break;
1822 case RELAUNCH_ACTIVITY: {
1823 ActivityRecord r = (ActivityRecord)msg.obj;
1824 handleRelaunchActivity(r, msg.arg1);
1825 } break;
1826 case PAUSE_ACTIVITY:
1827 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001828 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 break;
1830 case PAUSE_ACTIVITY_FINISHING:
1831 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1832 break;
1833 case STOP_ACTIVITY_SHOW:
1834 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1835 break;
1836 case STOP_ACTIVITY_HIDE:
1837 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1838 break;
1839 case SHOW_WINDOW:
1840 handleWindowVisibility((IBinder)msg.obj, true);
1841 break;
1842 case HIDE_WINDOW:
1843 handleWindowVisibility((IBinder)msg.obj, false);
1844 break;
1845 case RESUME_ACTIVITY:
1846 handleResumeActivity((IBinder)msg.obj, true,
1847 msg.arg1 != 0);
1848 break;
1849 case SEND_RESULT:
1850 handleSendResult((ResultData)msg.obj);
1851 break;
1852 case DESTROY_ACTIVITY:
1853 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1854 msg.arg2, false);
1855 break;
1856 case BIND_APPLICATION:
1857 AppBindData data = (AppBindData)msg.obj;
1858 handleBindApplication(data);
1859 break;
1860 case EXIT_APPLICATION:
1861 if (mInitialApplication != null) {
1862 mInitialApplication.onTerminate();
1863 }
1864 Looper.myLooper().quit();
1865 break;
1866 case NEW_INTENT:
1867 handleNewIntent((NewIntentData)msg.obj);
1868 break;
1869 case RECEIVER:
1870 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001871 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 break;
1873 case CREATE_SERVICE:
1874 handleCreateService((CreateServiceData)msg.obj);
1875 break;
1876 case BIND_SERVICE:
1877 handleBindService((BindServiceData)msg.obj);
1878 break;
1879 case UNBIND_SERVICE:
1880 handleUnbindService((BindServiceData)msg.obj);
1881 break;
1882 case SERVICE_ARGS:
1883 handleServiceArgs((ServiceArgsData)msg.obj);
1884 break;
1885 case STOP_SERVICE:
1886 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001887 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 break;
1889 case REQUEST_THUMBNAIL:
1890 handleRequestThumbnail((IBinder)msg.obj);
1891 break;
1892 case CONFIGURATION_CHANGED:
1893 handleConfigurationChanged((Configuration)msg.obj);
1894 break;
1895 case CLEAN_UP_CONTEXT:
1896 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1897 cci.context.performFinalCleanup(cci.who, cci.what);
1898 break;
1899 case GC_WHEN_IDLE:
1900 scheduleGcIdler();
1901 break;
1902 case DUMP_SERVICE:
1903 handleDumpService((DumpServiceInfo)msg.obj);
1904 break;
1905 case LOW_MEMORY:
1906 handleLowMemory();
1907 break;
1908 case ACTIVITY_CONFIGURATION_CHANGED:
1909 handleActivityConfigurationChanged((IBinder)msg.obj);
1910 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001911 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001912 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001913 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001914 case CREATE_BACKUP_AGENT:
1915 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1916 break;
1917 case DESTROY_BACKUP_AGENT:
1918 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1919 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001920 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001921 Process.killProcess(Process.myPid());
1922 break;
1923 case REMOVE_PROVIDER:
1924 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001925 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 }
1927 }
Bob Leee5408332009-09-04 18:31:17 -07001928
1929 void maybeSnapshot() {
1930 if (mBoundApplication != null) {
1931 SamplingProfilerIntegration.writeSnapshot(
1932 mBoundApplication.processName);
1933 }
1934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
1936
1937 private final class Idler implements MessageQueue.IdleHandler {
1938 public final boolean queueIdle() {
1939 ActivityRecord a = mNewActivities;
1940 if (a != null) {
1941 mNewActivities = null;
1942 IActivityManager am = ActivityManagerNative.getDefault();
1943 ActivityRecord prev;
1944 do {
1945 if (localLOGV) Log.v(
1946 TAG, "Reporting idle of " + a +
1947 " finished=" +
1948 (a.activity != null ? a.activity.mFinished : false));
1949 if (a.activity != null && !a.activity.mFinished) {
1950 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001951 am.activityIdle(a.token, a.createdConfig);
1952 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 } catch (RemoteException ex) {
1954 }
1955 }
1956 prev = a;
1957 a = a.nextIdle;
1958 prev.nextIdle = null;
1959 } while (a != null);
1960 }
1961 return false;
1962 }
1963 }
1964
1965 final class GcIdler implements MessageQueue.IdleHandler {
1966 public final boolean queueIdle() {
1967 doGcIfNeeded();
1968 return false;
1969 }
1970 }
1971
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001972 private final static class ResourcesKey {
1973 final private String mResDir;
1974 final private float mScale;
1975 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001976
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001977 ResourcesKey(String resDir, float scale) {
1978 mResDir = resDir;
1979 mScale = scale;
1980 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1981 }
Bob Leee5408332009-09-04 18:31:17 -07001982
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001983 @Override
1984 public int hashCode() {
1985 return mHash;
1986 }
1987
1988 @Override
1989 public boolean equals(Object obj) {
1990 if (!(obj instanceof ResourcesKey)) {
1991 return false;
1992 }
1993 ResourcesKey peer = (ResourcesKey) obj;
1994 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1995 }
1996 }
1997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 static IPackageManager sPackageManager;
1999
2000 final ApplicationThread mAppThread = new ApplicationThread();
2001 final Looper mLooper = Looper.myLooper();
2002 final H mH = new H();
2003 final HashMap<IBinder, ActivityRecord> mActivities
2004 = new HashMap<IBinder, ActivityRecord>();
2005 // List of new activities (via ActivityRecord.nextIdle) that should
2006 // be reported when next we idle.
2007 ActivityRecord mNewActivities = null;
2008 // Number of activities that are currently visible on-screen.
2009 int mNumVisibleActivities = 0;
2010 final HashMap<IBinder, Service> mServices
2011 = new HashMap<IBinder, Service>();
2012 AppBindData mBoundApplication;
2013 Configuration mConfiguration;
2014 Application mInitialApplication;
2015 final ArrayList<Application> mAllApplications
2016 = new ArrayList<Application>();
Christopher Tate181fafa2009-05-14 11:12:14 -07002017 // set of instantiated backup agents, keyed by package name
2018 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 static final ThreadLocal sThreadLocal = new ThreadLocal();
2020 Instrumentation mInstrumentation;
2021 String mInstrumentationAppDir = null;
2022 String mInstrumentationAppPackage = null;
2023 String mInstrumentedAppDir = null;
2024 boolean mSystemThread = false;
2025
2026 /**
2027 * Activities that are enqueued to be relaunched. This list is accessed
2028 * by multiple threads, so you must synchronize on it when accessing it.
2029 */
2030 final ArrayList<ActivityRecord> mRelaunchingActivities
2031 = new ArrayList<ActivityRecord>();
2032 Configuration mPendingConfiguration = null;
Bob Leee5408332009-09-04 18:31:17 -07002033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 // These can be accessed by multiple threads; mPackages is the lock.
2035 // XXX For now we keep around information about all packages we have
2036 // seen, not removing entries from this map.
2037 final HashMap<String, WeakReference<PackageInfo>> mPackages
2038 = new HashMap<String, WeakReference<PackageInfo>>();
2039 final HashMap<String, WeakReference<PackageInfo>> mResourcePackages
2040 = new HashMap<String, WeakReference<PackageInfo>>();
2041 Display mDisplay = null;
2042 DisplayMetrics mDisplayMetrics = null;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002043 HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
2044 = new HashMap<ResourcesKey, WeakReference<Resources> >();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045
2046 // The lock of mProviderMap protects the following variables.
2047 final HashMap<String, ProviderRecord> mProviderMap
2048 = new HashMap<String, ProviderRecord>();
2049 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
2050 = new HashMap<IBinder, ProviderRefCount>();
2051 final HashMap<IBinder, ProviderRecord> mLocalProviders
2052 = new HashMap<IBinder, ProviderRecord>();
2053
2054 final GcIdler mGcIdler = new GcIdler();
2055 boolean mGcIdlerScheduled = false;
2056
2057 public final PackageInfo getPackageInfo(String packageName, int flags) {
2058 synchronized (mPackages) {
2059 WeakReference<PackageInfo> ref;
2060 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
2061 ref = mPackages.get(packageName);
2062 } else {
2063 ref = mResourcePackages.get(packageName);
2064 }
2065 PackageInfo packageInfo = ref != null ? ref.get() : null;
2066 //Log.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
2067 if (packageInfo != null && (packageInfo.mResources == null
2068 || packageInfo.mResources.getAssets().isUpToDate())) {
2069 if (packageInfo.isSecurityViolation()
2070 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2071 throw new SecurityException(
2072 "Requesting code from " + packageName
2073 + " to be run in process "
2074 + mBoundApplication.processName
2075 + "/" + mBoundApplication.appInfo.uid);
2076 }
2077 return packageInfo;
2078 }
2079 }
2080
2081 ApplicationInfo ai = null;
2082 try {
2083 ai = getPackageManager().getApplicationInfo(packageName,
2084 PackageManager.GET_SHARED_LIBRARY_FILES);
2085 } catch (RemoteException e) {
2086 }
2087
2088 if (ai != null) {
2089 return getPackageInfo(ai, flags);
2090 }
2091
2092 return null;
2093 }
2094
2095 public final PackageInfo getPackageInfo(ApplicationInfo ai, int flags) {
2096 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2097 boolean securityViolation = includeCode && ai.uid != 0
2098 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
2099 ? ai.uid != mBoundApplication.appInfo.uid : true);
2100 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2101 |Context.CONTEXT_IGNORE_SECURITY))
2102 == Context.CONTEXT_INCLUDE_CODE) {
2103 if (securityViolation) {
2104 String msg = "Requesting code from " + ai.packageName
2105 + " (with uid " + ai.uid + ")";
2106 if (mBoundApplication != null) {
2107 msg = msg + " to be run in process "
2108 + mBoundApplication.processName + " (with uid "
2109 + mBoundApplication.appInfo.uid + ")";
2110 }
2111 throw new SecurityException(msg);
2112 }
2113 }
2114 return getPackageInfo(ai, null, securityViolation, includeCode);
2115 }
2116
2117 public final PackageInfo getPackageInfoNoCheck(ApplicationInfo ai) {
2118 return getPackageInfo(ai, null, false, true);
2119 }
2120
2121 private final PackageInfo getPackageInfo(ApplicationInfo aInfo,
2122 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
2123 synchronized (mPackages) {
2124 WeakReference<PackageInfo> ref;
2125 if (includeCode) {
2126 ref = mPackages.get(aInfo.packageName);
2127 } else {
2128 ref = mResourcePackages.get(aInfo.packageName);
2129 }
2130 PackageInfo packageInfo = ref != null ? ref.get() : null;
2131 if (packageInfo == null || (packageInfo.mResources != null
2132 && !packageInfo.mResources.getAssets().isUpToDate())) {
2133 if (localLOGV) Log.v(TAG, (includeCode ? "Loading code package "
2134 : "Loading resource-only package ") + aInfo.packageName
2135 + " (in " + (mBoundApplication != null
2136 ? mBoundApplication.processName : null)
2137 + ")");
2138 packageInfo =
2139 new PackageInfo(this, aInfo, this, baseLoader,
2140 securityViolation, includeCode &&
2141 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
2142 if (includeCode) {
2143 mPackages.put(aInfo.packageName,
2144 new WeakReference<PackageInfo>(packageInfo));
2145 } else {
2146 mResourcePackages.put(aInfo.packageName,
2147 new WeakReference<PackageInfo>(packageInfo));
2148 }
2149 }
2150 return packageInfo;
2151 }
2152 }
2153
2154 public final boolean hasPackageInfo(String packageName) {
2155 synchronized (mPackages) {
2156 WeakReference<PackageInfo> ref;
2157 ref = mPackages.get(packageName);
2158 if (ref != null && ref.get() != null) {
2159 return true;
2160 }
2161 ref = mResourcePackages.get(packageName);
2162 if (ref != null && ref.get() != null) {
2163 return true;
2164 }
2165 return false;
2166 }
2167 }
Bob Leee5408332009-09-04 18:31:17 -07002168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 ActivityThread() {
2170 }
2171
2172 public ApplicationThread getApplicationThread()
2173 {
2174 return mAppThread;
2175 }
2176
2177 public Instrumentation getInstrumentation()
2178 {
2179 return mInstrumentation;
2180 }
2181
2182 public Configuration getConfiguration() {
2183 return mConfiguration;
2184 }
2185
2186 public boolean isProfiling() {
2187 return mBoundApplication != null && mBoundApplication.profileFile != null;
2188 }
2189
2190 public String getProfileFilePath() {
2191 return mBoundApplication.profileFile;
2192 }
2193
2194 public Looper getLooper() {
2195 return mLooper;
2196 }
2197
2198 public Application getApplication() {
2199 return mInitialApplication;
2200 }
Bob Leee5408332009-09-04 18:31:17 -07002201
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002202 public String getProcessName() {
2203 return mBoundApplication.processName;
2204 }
Bob Leee5408332009-09-04 18:31:17 -07002205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 public ApplicationContext getSystemContext() {
2207 synchronized (this) {
2208 if (mSystemContext == null) {
2209 ApplicationContext context =
2210 ApplicationContext.createSystemContext(this);
Mike Cleron432b7132009-09-24 15:28:29 -07002211 PackageInfo info = new PackageInfo(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 context.init(info, null, this);
2213 context.getResources().updateConfiguration(
2214 getConfiguration(), getDisplayMetricsLocked(false));
2215 mSystemContext = context;
2216 //Log.i(TAG, "Created system resources " + context.getResources()
2217 // + ": " + context.getResources().getConfiguration());
2218 }
2219 }
2220 return mSystemContext;
2221 }
2222
Mike Cleron432b7132009-09-24 15:28:29 -07002223 public void installSystemApplicationInfo(ApplicationInfo info) {
2224 synchronized (this) {
2225 ApplicationContext context = getSystemContext();
2226 context.init(new PackageInfo(this, "android", context, info), null, this);
2227 }
2228 }
2229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 void scheduleGcIdler() {
2231 if (!mGcIdlerScheduled) {
2232 mGcIdlerScheduled = true;
2233 Looper.myQueue().addIdleHandler(mGcIdler);
2234 }
2235 mH.removeMessages(H.GC_WHEN_IDLE);
2236 }
2237
2238 void unscheduleGcIdler() {
2239 if (mGcIdlerScheduled) {
2240 mGcIdlerScheduled = false;
2241 Looper.myQueue().removeIdleHandler(mGcIdler);
2242 }
2243 mH.removeMessages(H.GC_WHEN_IDLE);
2244 }
2245
2246 void doGcIfNeeded() {
2247 mGcIdlerScheduled = false;
2248 final long now = SystemClock.uptimeMillis();
2249 //Log.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
2250 // + "m now=" + now);
2251 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
2252 //Log.i(TAG, "**** WE DO, WE DO WANT TO GC!");
2253 BinderInternal.forceGc("bg");
2254 }
2255 }
2256
2257 public final ActivityInfo resolveActivityInfo(Intent intent) {
2258 ActivityInfo aInfo = intent.resolveActivityInfo(
2259 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2260 if (aInfo == null) {
2261 // Throw an exception.
2262 Instrumentation.checkStartActivityResult(
2263 IActivityManager.START_CLASS_NOT_FOUND, intent);
2264 }
2265 return aInfo;
2266 }
Bob Leee5408332009-09-04 18:31:17 -07002267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
2270 Object lastNonConfigurationInstance) {
2271 ActivityRecord r = new ActivityRecord();
2272 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002273 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 r.intent = intent;
2275 r.state = state;
2276 r.parent = parent;
2277 r.embeddedID = id;
2278 r.activityInfo = activityInfo;
2279 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
2280 if (localLOGV) {
2281 ComponentName compname = intent.getComponent();
2282 String name;
2283 if (compname != null) {
2284 name = compname.toShortString();
2285 } else {
2286 name = "(Intent " + intent + ").getComponent() returned null";
2287 }
2288 Log.v(TAG, "Performing launch: action=" + intent.getAction()
2289 + ", comp=" + name
2290 + ", token=" + token);
2291 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07002292 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 }
2294
2295 public final Activity getActivity(IBinder token) {
2296 return mActivities.get(token).activity;
2297 }
2298
2299 public final void sendActivityResult(
2300 IBinder token, String id, int requestCode,
2301 int resultCode, Intent data) {
Chris Tate8a7dc172009-03-24 20:11:42 -07002302 if (DEBUG_RESULTS) Log.v(TAG, "sendActivityResult: id=" + id
2303 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2305 list.add(new ResultInfo(id, requestCode, resultCode, data));
2306 mAppThread.scheduleSendResult(token, list);
2307 }
2308
2309 // if the thread hasn't started yet, we don't have the handler, so just
2310 // save the messages until we're ready.
2311 private final void queueOrSendMessage(int what, Object obj) {
2312 queueOrSendMessage(what, obj, 0, 0);
2313 }
2314
2315 private final void queueOrSendMessage(int what, Object obj, int arg1) {
2316 queueOrSendMessage(what, obj, arg1, 0);
2317 }
2318
2319 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
2320 synchronized (this) {
2321 if (localLOGV) Log.v(
2322 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2323 + ": " + arg1 + " / " + obj);
2324 Message msg = Message.obtain();
2325 msg.what = what;
2326 msg.obj = obj;
2327 msg.arg1 = arg1;
2328 msg.arg2 = arg2;
2329 mH.sendMessage(msg);
2330 }
2331 }
2332
2333 final void scheduleContextCleanup(ApplicationContext context, String who,
2334 String what) {
2335 ContextCleanupInfo cci = new ContextCleanupInfo();
2336 cci.context = context;
2337 cci.who = who;
2338 cci.what = what;
2339 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
2340 }
2341
Christopher Tateb70f3df2009-04-07 16:07:59 -07002342 private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
2344
2345 ActivityInfo aInfo = r.activityInfo;
2346 if (r.packageInfo == null) {
2347 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
2348 Context.CONTEXT_INCLUDE_CODE);
2349 }
Bob Leee5408332009-09-04 18:31:17 -07002350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 ComponentName component = r.intent.getComponent();
2352 if (component == null) {
2353 component = r.intent.resolveActivity(
2354 mInitialApplication.getPackageManager());
2355 r.intent.setComponent(component);
2356 }
2357
2358 if (r.activityInfo.targetActivity != null) {
2359 component = new ComponentName(r.activityInfo.packageName,
2360 r.activityInfo.targetActivity);
2361 }
2362
2363 Activity activity = null;
2364 try {
2365 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
2366 activity = mInstrumentation.newActivity(
2367 cl, component.getClassName(), r.intent);
2368 r.intent.setExtrasClassLoader(cl);
2369 if (r.state != null) {
2370 r.state.setClassLoader(cl);
2371 }
2372 } catch (Exception e) {
2373 if (!mInstrumentation.onException(activity, e)) {
2374 throw new RuntimeException(
2375 "Unable to instantiate activity " + component
2376 + ": " + e.toString(), e);
2377 }
2378 }
2379
2380 try {
Christopher Tate181fafa2009-05-14 11:12:14 -07002381 Application app = r.packageInfo.makeApplication(false);
Bob Leee5408332009-09-04 18:31:17 -07002382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 if (localLOGV) Log.v(TAG, "Performing launch of " + r);
2384 if (localLOGV) Log.v(
2385 TAG, r + ": app=" + app
2386 + ", appName=" + app.getPackageName()
2387 + ", pkg=" + r.packageInfo.getPackageName()
2388 + ", comp=" + r.intent.getComponent().toShortString()
2389 + ", dir=" + r.packageInfo.getAppDir());
2390
2391 if (activity != null) {
2392 ApplicationContext appContext = new ApplicationContext();
2393 appContext.init(r.packageInfo, r.token, this);
2394 appContext.setOuterContext(activity);
2395 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
2396 Configuration config = new Configuration(mConfiguration);
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002397 if (DEBUG_CONFIGURATION) Log.v(TAG, "Launching activity "
2398 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002399 activity.attach(appContext, this, getInstrumentation(), r.token,
2400 r.ident, app, r.intent, r.activityInfo, title, r.parent,
2401 r.embeddedID, r.lastNonConfigurationInstance,
2402 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07002403
Christopher Tateb70f3df2009-04-07 16:07:59 -07002404 if (customIntent != null) {
2405 activity.mIntent = customIntent;
2406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 r.lastNonConfigurationInstance = null;
2408 r.lastNonConfigurationChildInstances = null;
2409 activity.mStartedActivity = false;
2410 int theme = r.activityInfo.getThemeResource();
2411 if (theme != 0) {
2412 activity.setTheme(theme);
2413 }
2414
2415 activity.mCalled = false;
2416 mInstrumentation.callActivityOnCreate(activity, r.state);
2417 if (!activity.mCalled) {
2418 throw new SuperNotCalledException(
2419 "Activity " + r.intent.getComponent().toShortString() +
2420 " did not call through to super.onCreate()");
2421 }
2422 r.activity = activity;
2423 r.stopped = true;
2424 if (!r.activity.mFinished) {
2425 activity.performStart();
2426 r.stopped = false;
2427 }
2428 if (!r.activity.mFinished) {
2429 if (r.state != null) {
2430 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2431 }
2432 }
2433 if (!r.activity.mFinished) {
2434 activity.mCalled = false;
2435 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2436 if (!activity.mCalled) {
2437 throw new SuperNotCalledException(
2438 "Activity " + r.intent.getComponent().toShortString() +
2439 " did not call through to super.onPostCreate()");
2440 }
2441 }
2442 r.state = null;
2443 }
2444 r.paused = true;
2445
2446 mActivities.put(r.token, r);
2447
2448 } catch (SuperNotCalledException e) {
2449 throw e;
2450
2451 } catch (Exception e) {
2452 if (!mInstrumentation.onException(activity, e)) {
2453 throw new RuntimeException(
2454 "Unable to start activity " + component
2455 + ": " + e.toString(), e);
2456 }
2457 }
2458
2459 return activity;
2460 }
2461
Christopher Tateb70f3df2009-04-07 16:07:59 -07002462 private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 // If we are getting ready to gc after going to the background, well
2464 // we are back active so skip it.
2465 unscheduleGcIdler();
2466
2467 if (localLOGV) Log.v(
2468 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002469 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470
2471 if (a != null) {
Dianne Hackborne88846e2009-09-30 21:34:25 -07002472 r.createdConfig = new Configuration(a.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 handleResumeActivity(r.token, false, r.isForward);
2474
2475 if (!r.activity.mFinished && r.startsNotResumed) {
2476 // The activity manager actually wants this one to start out
2477 // paused, because it needs to be visible but isn't in the
2478 // foreground. We accomplish this by going through the
2479 // normal startup (because activities expect to go through
2480 // onResume() the first time they run, before their window
2481 // is displayed), and then pausing it. However, in this case
2482 // we do -not- need to do the full pause cycle (of freezing
2483 // and such) because the activity manager assumes it can just
2484 // retain the current state it has.
2485 try {
2486 r.activity.mCalled = false;
2487 mInstrumentation.callActivityOnPause(r.activity);
2488 if (!r.activity.mCalled) {
2489 throw new SuperNotCalledException(
2490 "Activity " + r.intent.getComponent().toShortString() +
2491 " did not call through to super.onPause()");
2492 }
2493
2494 } catch (SuperNotCalledException e) {
2495 throw e;
2496
2497 } catch (Exception e) {
2498 if (!mInstrumentation.onException(r.activity, e)) {
2499 throw new RuntimeException(
2500 "Unable to pause activity "
2501 + r.intent.getComponent().toShortString()
2502 + ": " + e.toString(), e);
2503 }
2504 }
2505 r.paused = true;
2506 }
2507 } else {
2508 // If there was an error, for any reason, tell the activity
2509 // manager to stop us.
2510 try {
2511 ActivityManagerNative.getDefault()
2512 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2513 } catch (RemoteException ex) {
2514 }
2515 }
2516 }
2517
2518 private final void deliverNewIntents(ActivityRecord r,
2519 List<Intent> intents) {
2520 final int N = intents.size();
2521 for (int i=0; i<N; i++) {
2522 Intent intent = intents.get(i);
2523 intent.setExtrasClassLoader(r.activity.getClassLoader());
2524 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2525 }
2526 }
2527
2528 public final void performNewIntents(IBinder token,
2529 List<Intent> intents) {
2530 ActivityRecord r = mActivities.get(token);
2531 if (r != null) {
2532 final boolean resumed = !r.paused;
2533 if (resumed) {
2534 mInstrumentation.callActivityOnPause(r.activity);
2535 }
2536 deliverNewIntents(r, intents);
2537 if (resumed) {
2538 mInstrumentation.callActivityOnResume(r.activity);
2539 }
2540 }
2541 }
Bob Leee5408332009-09-04 18:31:17 -07002542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 private final void handleNewIntent(NewIntentData data) {
2544 performNewIntents(data.token, data.intents);
2545 }
2546
2547 private final void handleReceiver(ReceiverData data) {
2548 // If we are getting ready to gc after going to the background, well
2549 // we are back active so skip it.
2550 unscheduleGcIdler();
2551
2552 String component = data.intent.getComponent().getClassName();
2553
2554 PackageInfo packageInfo = getPackageInfoNoCheck(
2555 data.info.applicationInfo);
2556
2557 IActivityManager mgr = ActivityManagerNative.getDefault();
2558
2559 BroadcastReceiver receiver = null;
2560 try {
2561 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2562 data.intent.setExtrasClassLoader(cl);
2563 if (data.resultExtras != null) {
2564 data.resultExtras.setClassLoader(cl);
2565 }
2566 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2567 } catch (Exception e) {
2568 try {
2569 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2570 data.resultData, data.resultExtras, data.resultAbort);
2571 } catch (RemoteException ex) {
2572 }
2573 throw new RuntimeException(
2574 "Unable to instantiate receiver " + component
2575 + ": " + e.toString(), e);
2576 }
2577
2578 try {
Christopher Tate181fafa2009-05-14 11:12:14 -07002579 Application app = packageInfo.makeApplication(false);
Bob Leee5408332009-09-04 18:31:17 -07002580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 if (localLOGV) Log.v(
2582 TAG, "Performing receive of " + data.intent
2583 + ": app=" + app
2584 + ", appName=" + app.getPackageName()
2585 + ", pkg=" + packageInfo.getPackageName()
2586 + ", comp=" + data.intent.getComponent().toShortString()
2587 + ", dir=" + packageInfo.getAppDir());
2588
2589 ApplicationContext context = (ApplicationContext)app.getBaseContext();
2590 receiver.setOrderedHint(true);
2591 receiver.setResult(data.resultCode, data.resultData,
2592 data.resultExtras);
2593 receiver.setOrderedHint(data.sync);
2594 receiver.onReceive(context.getReceiverRestrictedContext(),
2595 data.intent);
2596 } catch (Exception e) {
2597 try {
2598 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2599 data.resultData, data.resultExtras, data.resultAbort);
2600 } catch (RemoteException ex) {
2601 }
2602 if (!mInstrumentation.onException(receiver, e)) {
2603 throw new RuntimeException(
2604 "Unable to start receiver " + component
2605 + ": " + e.toString(), e);
2606 }
2607 }
2608
2609 try {
2610 if (data.sync) {
2611 mgr.finishReceiver(
2612 mAppThread.asBinder(), receiver.getResultCode(),
2613 receiver.getResultData(), receiver.getResultExtras(false),
2614 receiver.getAbortBroadcast());
2615 } else {
2616 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
2617 }
2618 } catch (RemoteException ex) {
2619 }
2620 }
2621
Christopher Tate181fafa2009-05-14 11:12:14 -07002622 // Instantiate a BackupAgent and tell it that it's alive
2623 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
2624 if (DEBUG_BACKUP) Log.v(TAG, "handleCreateBackupAgent: " + data);
2625
2626 // no longer idle; we have backup work to do
2627 unscheduleGcIdler();
2628
2629 // instantiate the BackupAgent class named in the manifest
2630 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2631 String packageName = packageInfo.mPackageName;
2632 if (mBackupAgents.get(packageName) != null) {
2633 Log.d(TAG, "BackupAgent " + " for " + packageName
2634 + " already exists");
2635 return;
2636 }
Bob Leee5408332009-09-04 18:31:17 -07002637
Christopher Tate181fafa2009-05-14 11:12:14 -07002638 BackupAgent agent = null;
2639 String classname = data.appInfo.backupAgentName;
2640 if (classname == null) {
2641 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
2642 Log.e(TAG, "Attempted incremental backup but no defined agent for "
2643 + packageName);
2644 return;
2645 }
2646 classname = "android.app.FullBackupAgent";
2647 }
2648 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002649 IBinder binder = null;
2650 try {
2651 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2652 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
2653
2654 // set up the agent's context
2655 if (DEBUG_BACKUP) Log.v(TAG, "Initializing BackupAgent "
2656 + data.appInfo.backupAgentName);
2657
2658 ApplicationContext context = new ApplicationContext();
2659 context.init(packageInfo, null, this);
2660 context.setOuterContext(agent);
2661 agent.attach(context);
2662
2663 agent.onCreate();
2664 binder = agent.onBind();
2665 mBackupAgents.put(packageName, agent);
2666 } catch (Exception e) {
2667 // If this is during restore, fail silently; otherwise go
2668 // ahead and let the user see the crash.
2669 Log.e(TAG, "Agent threw during creation: " + e);
2670 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
2671 throw e;
2672 }
2673 // falling through with 'binder' still null
2674 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002675
2676 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002677 try {
2678 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2679 } catch (RemoteException e) {
2680 // nothing to do.
2681 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002682 } catch (Exception e) {
2683 throw new RuntimeException("Unable to create BackupAgent "
2684 + data.appInfo.backupAgentName + ": " + e.toString(), e);
2685 }
2686 }
2687
2688 // Tear down a BackupAgent
2689 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
2690 if (DEBUG_BACKUP) Log.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002691
Christopher Tate181fafa2009-05-14 11:12:14 -07002692 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2693 String packageName = packageInfo.mPackageName;
2694 BackupAgent agent = mBackupAgents.get(packageName);
2695 if (agent != null) {
2696 try {
2697 agent.onDestroy();
2698 } catch (Exception e) {
2699 Log.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
2700 e.printStackTrace();
2701 }
2702 mBackupAgents.remove(packageName);
2703 } else {
2704 Log.w(TAG, "Attempt to destroy unknown backup agent " + data);
2705 }
2706 }
2707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 private final void handleCreateService(CreateServiceData data) {
2709 // If we are getting ready to gc after going to the background, well
2710 // we are back active so skip it.
2711 unscheduleGcIdler();
2712
2713 PackageInfo packageInfo = getPackageInfoNoCheck(
2714 data.info.applicationInfo);
2715 Service service = null;
2716 try {
2717 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2718 service = (Service) cl.loadClass(data.info.name).newInstance();
2719 } catch (Exception e) {
2720 if (!mInstrumentation.onException(service, e)) {
2721 throw new RuntimeException(
2722 "Unable to instantiate service " + data.info.name
2723 + ": " + e.toString(), e);
2724 }
2725 }
2726
2727 try {
2728 if (localLOGV) Log.v(TAG, "Creating service " + data.info.name);
2729
2730 ApplicationContext context = new ApplicationContext();
2731 context.init(packageInfo, null, this);
2732
Christopher Tate181fafa2009-05-14 11:12:14 -07002733 Application app = packageInfo.makeApplication(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 context.setOuterContext(service);
2735 service.attach(context, this, data.info.name, data.token, app,
2736 ActivityManagerNative.getDefault());
2737 service.onCreate();
2738 mServices.put(data.token, service);
2739 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002740 ActivityManagerNative.getDefault().serviceDoneExecuting(
2741 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 } catch (RemoteException e) {
2743 // nothing to do.
2744 }
2745 } catch (Exception e) {
2746 if (!mInstrumentation.onException(service, e)) {
2747 throw new RuntimeException(
2748 "Unable to create service " + data.info.name
2749 + ": " + e.toString(), e);
2750 }
2751 }
2752 }
2753
2754 private final void handleBindService(BindServiceData data) {
2755 Service s = mServices.get(data.token);
2756 if (s != null) {
2757 try {
2758 data.intent.setExtrasClassLoader(s.getClassLoader());
2759 try {
2760 if (!data.rebind) {
2761 IBinder binder = s.onBind(data.intent);
2762 ActivityManagerNative.getDefault().publishService(
2763 data.token, data.intent, binder);
2764 } else {
2765 s.onRebind(data.intent);
2766 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002767 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 }
2769 } catch (RemoteException ex) {
2770 }
2771 } catch (Exception e) {
2772 if (!mInstrumentation.onException(s, e)) {
2773 throw new RuntimeException(
2774 "Unable to bind to service " + s
2775 + " with " + data.intent + ": " + e.toString(), e);
2776 }
2777 }
2778 }
2779 }
2780
2781 private final void handleUnbindService(BindServiceData data) {
2782 Service s = mServices.get(data.token);
2783 if (s != null) {
2784 try {
2785 data.intent.setExtrasClassLoader(s.getClassLoader());
2786 boolean doRebind = s.onUnbind(data.intent);
2787 try {
2788 if (doRebind) {
2789 ActivityManagerNative.getDefault().unbindFinished(
2790 data.token, data.intent, doRebind);
2791 } else {
2792 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002793 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 }
2795 } catch (RemoteException ex) {
2796 }
2797 } catch (Exception e) {
2798 if (!mInstrumentation.onException(s, e)) {
2799 throw new RuntimeException(
2800 "Unable to unbind to service " + s
2801 + " with " + data.intent + ": " + e.toString(), e);
2802 }
2803 }
2804 }
2805 }
2806
2807 private void handleDumpService(DumpServiceInfo info) {
2808 try {
2809 Service s = mServices.get(info.service);
2810 if (s != null) {
2811 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2812 s.dump(info.fd, pw, info.args);
2813 pw.close();
2814 }
2815 } finally {
2816 synchronized (info) {
2817 info.dumped = true;
2818 info.notifyAll();
2819 }
2820 }
2821 }
2822
2823 private final void handleServiceArgs(ServiceArgsData data) {
2824 Service s = mServices.get(data.token);
2825 if (s != null) {
2826 try {
2827 if (data.args != null) {
2828 data.args.setExtrasClassLoader(s.getClassLoader());
2829 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002830 int res = s.onStartCommand(data.args, data.flags, data.startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002832 ActivityManagerNative.getDefault().serviceDoneExecuting(
2833 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 } catch (RemoteException e) {
2835 // nothing to do.
2836 }
2837 } catch (Exception e) {
2838 if (!mInstrumentation.onException(s, e)) {
2839 throw new RuntimeException(
2840 "Unable to start service " + s
2841 + " with " + data.args + ": " + e.toString(), e);
2842 }
2843 }
2844 }
2845 }
2846
2847 private final void handleStopService(IBinder token) {
2848 Service s = mServices.remove(token);
2849 if (s != null) {
2850 try {
2851 if (localLOGV) Log.v(TAG, "Destroying service " + s);
2852 s.onDestroy();
2853 Context context = s.getBaseContext();
2854 if (context instanceof ApplicationContext) {
2855 final String who = s.getClassName();
2856 ((ApplicationContext) context).scheduleFinalCleanup(who, "Service");
2857 }
2858 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002859 ActivityManagerNative.getDefault().serviceDoneExecuting(
2860 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 } catch (RemoteException e) {
2862 // nothing to do.
2863 }
2864 } catch (Exception e) {
2865 if (!mInstrumentation.onException(s, e)) {
2866 throw new RuntimeException(
2867 "Unable to stop service " + s
2868 + ": " + e.toString(), e);
2869 }
2870 }
2871 }
2872 //Log.i(TAG, "Running services: " + mServices);
2873 }
2874
2875 public final ActivityRecord performResumeActivity(IBinder token,
2876 boolean clearHide) {
2877 ActivityRecord r = mActivities.get(token);
2878 if (localLOGV) Log.v(TAG, "Performing resume of " + r
2879 + " finished=" + r.activity.mFinished);
2880 if (r != null && !r.activity.mFinished) {
2881 if (clearHide) {
2882 r.hideForNow = false;
2883 r.activity.mStartedActivity = false;
2884 }
2885 try {
2886 if (r.pendingIntents != null) {
2887 deliverNewIntents(r, r.pendingIntents);
2888 r.pendingIntents = null;
2889 }
2890 if (r.pendingResults != null) {
2891 deliverResults(r, r.pendingResults);
2892 r.pendingResults = null;
2893 }
2894 r.activity.performResume();
2895
Bob Leee5408332009-09-04 18:31:17 -07002896 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 r.paused = false;
2900 r.stopped = false;
2901 if (r.activity.mStartedActivity) {
2902 r.hideForNow = true;
2903 }
2904 r.state = null;
2905 } catch (Exception e) {
2906 if (!mInstrumentation.onException(r.activity, e)) {
2907 throw new RuntimeException(
2908 "Unable to resume activity "
2909 + r.intent.getComponent().toShortString()
2910 + ": " + e.toString(), e);
2911 }
2912 }
2913 }
2914 return r;
2915 }
2916
2917 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2918 // If we are getting ready to gc after going to the background, well
2919 // we are back active so skip it.
2920 unscheduleGcIdler();
2921
2922 ActivityRecord r = performResumeActivity(token, clearHide);
2923
2924 if (r != null) {
2925 final Activity a = r.activity;
2926
2927 if (localLOGV) Log.v(
2928 TAG, "Resume " + r + " started activity: " +
2929 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2930 + ", finished: " + a.mFinished);
2931
2932 final int forwardBit = isForward ?
2933 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 // If the window hasn't yet been added to the window manager,
2936 // and this guy didn't finish itself or start another activity,
2937 // then go ahead and add the window.
2938 if (r.window == null && !a.mFinished && !a.mStartedActivity) {
2939 r.window = r.activity.getWindow();
2940 View decor = r.window.getDecorView();
2941 decor.setVisibility(View.INVISIBLE);
2942 ViewManager wm = a.getWindowManager();
2943 WindowManager.LayoutParams l = r.window.getAttributes();
2944 a.mDecor = decor;
2945 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2946 l.softInputMode |= forwardBit;
2947 if (a.mVisibleFromClient) {
2948 a.mWindowAdded = true;
2949 wm.addView(decor, l);
2950 }
2951
2952 // If the window has already been added, but during resume
2953 // we started another activity, then don't yet make the
2954 // window visisble.
2955 } else if (a.mStartedActivity) {
2956 if (localLOGV) Log.v(
2957 TAG, "Launch " + r + " mStartedActivity set");
2958 r.hideForNow = true;
2959 }
2960
2961 // The window is now visible if it has been added, we are not
2962 // simply finishing, and we are not starting another activity.
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002963 if (!r.activity.mFinished && !a.mStartedActivity
2964 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 if (r.newConfig != null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002966 if (DEBUG_CONFIGURATION) Log.v(TAG, "Resuming activity "
2967 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 performConfigurationChanged(r.activity, r.newConfig);
2969 r.newConfig = null;
2970 }
2971 if (localLOGV) Log.v(TAG, "Resuming " + r + " with isForward="
2972 + isForward);
2973 WindowManager.LayoutParams l = r.window.getAttributes();
2974 if ((l.softInputMode
2975 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2976 != forwardBit) {
2977 l.softInputMode = (l.softInputMode
2978 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2979 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002980 if (r.activity.mVisibleFromClient) {
2981 ViewManager wm = a.getWindowManager();
2982 View decor = r.window.getDecorView();
2983 wm.updateViewLayout(decor, l);
2984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 }
2986 r.activity.mVisibleFromServer = true;
2987 mNumVisibleActivities++;
2988 if (r.activity.mVisibleFromClient) {
2989 r.activity.makeVisible();
2990 }
2991 }
2992
2993 r.nextIdle = mNewActivities;
2994 mNewActivities = r;
2995 if (localLOGV) Log.v(
2996 TAG, "Scheduling idle handler for " + r);
2997 Looper.myQueue().addIdleHandler(new Idler());
2998
2999 } else {
3000 // If an exception was thrown when trying to resume, then
3001 // just end this activity.
3002 try {
3003 ActivityManagerNative.getDefault()
3004 .finishActivity(token, Activity.RESULT_CANCELED, null);
3005 } catch (RemoteException ex) {
3006 }
3007 }
3008 }
3009
3010 private int mThumbnailWidth = -1;
3011 private int mThumbnailHeight = -1;
3012
3013 private final Bitmap createThumbnailBitmap(ActivityRecord r) {
3014 Bitmap thumbnail = null;
3015 try {
3016 int w = mThumbnailWidth;
3017 int h;
3018 if (w < 0) {
3019 Resources res = r.activity.getResources();
3020 mThumbnailHeight = h =
3021 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
3022
3023 mThumbnailWidth = w =
3024 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
3025 } else {
3026 h = mThumbnailHeight;
3027 }
3028
3029 // XXX Only set hasAlpha if needed?
3030 thumbnail = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
3031 thumbnail.eraseColor(0);
3032 Canvas cv = new Canvas(thumbnail);
3033 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
3034 thumbnail = null;
3035 }
3036 } catch (Exception e) {
3037 if (!mInstrumentation.onException(r.activity, e)) {
3038 throw new RuntimeException(
3039 "Unable to create thumbnail of "
3040 + r.intent.getComponent().toShortString()
3041 + ": " + e.toString(), e);
3042 }
3043 thumbnail = null;
3044 }
3045
3046 return thumbnail;
3047 }
3048
3049 private final void handlePauseActivity(IBinder token, boolean finished,
3050 boolean userLeaving, int configChanges) {
3051 ActivityRecord r = mActivities.get(token);
3052 if (r != null) {
3053 //Log.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
3054 if (userLeaving) {
3055 performUserLeavingActivity(r);
3056 }
Bob Leee5408332009-09-04 18:31:17 -07003057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 r.activity.mConfigChangeFlags |= configChanges;
3059 Bundle state = performPauseActivity(token, finished, true);
3060
3061 // Tell the activity manager we have paused.
3062 try {
3063 ActivityManagerNative.getDefault().activityPaused(token, state);
3064 } catch (RemoteException ex) {
3065 }
3066 }
3067 }
3068
3069 final void performUserLeavingActivity(ActivityRecord r) {
3070 mInstrumentation.callActivityOnUserLeaving(r.activity);
3071 }
3072
3073 final Bundle performPauseActivity(IBinder token, boolean finished,
3074 boolean saveState) {
3075 ActivityRecord r = mActivities.get(token);
3076 return r != null ? performPauseActivity(r, finished, saveState) : null;
3077 }
3078
3079 final Bundle performPauseActivity(ActivityRecord r, boolean finished,
3080 boolean saveState) {
3081 if (r.paused) {
3082 if (r.activity.mFinished) {
3083 // If we are finishing, we won't call onResume() in certain cases.
3084 // So here we likewise don't want to call onPause() if the activity
3085 // isn't resumed.
3086 return null;
3087 }
3088 RuntimeException e = new RuntimeException(
3089 "Performing pause of activity that is not resumed: "
3090 + r.intent.getComponent().toShortString());
3091 Log.e(TAG, e.getMessage(), e);
3092 }
3093 Bundle state = null;
3094 if (finished) {
3095 r.activity.mFinished = true;
3096 }
3097 try {
3098 // Next have the activity save its current state and managed dialogs...
3099 if (!r.activity.mFinished && saveState) {
3100 state = new Bundle();
3101 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
3102 r.state = state;
3103 }
3104 // Now we are idle.
3105 r.activity.mCalled = false;
3106 mInstrumentation.callActivityOnPause(r.activity);
3107 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
3108 if (!r.activity.mCalled) {
3109 throw new SuperNotCalledException(
3110 "Activity " + r.intent.getComponent().toShortString() +
3111 " did not call through to super.onPause()");
3112 }
3113
3114 } catch (SuperNotCalledException e) {
3115 throw e;
3116
3117 } catch (Exception e) {
3118 if (!mInstrumentation.onException(r.activity, e)) {
3119 throw new RuntimeException(
3120 "Unable to pause activity "
3121 + r.intent.getComponent().toShortString()
3122 + ": " + e.toString(), e);
3123 }
3124 }
3125 r.paused = true;
3126 return state;
3127 }
3128
3129 final void performStopActivity(IBinder token) {
3130 ActivityRecord r = mActivities.get(token);
3131 performStopActivityInner(r, null, false);
3132 }
3133
3134 private static class StopInfo {
3135 Bitmap thumbnail;
3136 CharSequence description;
3137 }
3138
3139 private final class ProviderRefCount {
3140 public int count;
3141 ProviderRefCount(int pCount) {
3142 count = pCount;
3143 }
3144 }
3145
3146 private final void performStopActivityInner(ActivityRecord r,
3147 StopInfo info, boolean keepShown) {
3148 if (localLOGV) Log.v(TAG, "Performing stop of " + r);
3149 if (r != null) {
3150 if (!keepShown && r.stopped) {
3151 if (r.activity.mFinished) {
3152 // If we are finishing, we won't call onResume() in certain
3153 // cases. So here we likewise don't want to call onStop()
3154 // if the activity isn't resumed.
3155 return;
3156 }
3157 RuntimeException e = new RuntimeException(
3158 "Performing stop of activity that is not resumed: "
3159 + r.intent.getComponent().toShortString());
3160 Log.e(TAG, e.getMessage(), e);
3161 }
3162
3163 if (info != null) {
3164 try {
3165 // First create a thumbnail for the activity...
3166 //info.thumbnail = createThumbnailBitmap(r);
3167 info.description = r.activity.onCreateDescription();
3168 } catch (Exception e) {
3169 if (!mInstrumentation.onException(r.activity, e)) {
3170 throw new RuntimeException(
3171 "Unable to save state of activity "
3172 + r.intent.getComponent().toShortString()
3173 + ": " + e.toString(), e);
3174 }
3175 }
3176 }
3177
3178 if (!keepShown) {
3179 try {
3180 // Now we are idle.
3181 r.activity.performStop();
3182 } catch (Exception e) {
3183 if (!mInstrumentation.onException(r.activity, e)) {
3184 throw new RuntimeException(
3185 "Unable to stop activity "
3186 + r.intent.getComponent().toShortString()
3187 + ": " + e.toString(), e);
3188 }
3189 }
3190 r.stopped = true;
3191 }
3192
3193 r.paused = true;
3194 }
3195 }
3196
3197 private final void updateVisibility(ActivityRecord r, boolean show) {
3198 View v = r.activity.mDecor;
3199 if (v != null) {
3200 if (show) {
3201 if (!r.activity.mVisibleFromServer) {
3202 r.activity.mVisibleFromServer = true;
3203 mNumVisibleActivities++;
3204 if (r.activity.mVisibleFromClient) {
3205 r.activity.makeVisible();
3206 }
3207 }
3208 if (r.newConfig != null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003209 if (DEBUG_CONFIGURATION) Log.v(TAG, "Updating activity vis "
3210 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 performConfigurationChanged(r.activity, r.newConfig);
3212 r.newConfig = null;
3213 }
3214 } else {
3215 if (r.activity.mVisibleFromServer) {
3216 r.activity.mVisibleFromServer = false;
3217 mNumVisibleActivities--;
3218 v.setVisibility(View.INVISIBLE);
3219 }
3220 }
3221 }
3222 }
3223
3224 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
3225 ActivityRecord r = mActivities.get(token);
3226 r.activity.mConfigChangeFlags |= configChanges;
3227
3228 StopInfo info = new StopInfo();
3229 performStopActivityInner(r, info, show);
3230
3231 if (localLOGV) Log.v(
3232 TAG, "Finishing stop of " + r + ": show=" + show
3233 + " win=" + r.window);
3234
3235 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07003236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 // Tell activity manager we have been stopped.
3238 try {
3239 ActivityManagerNative.getDefault().activityStopped(
3240 r.token, info.thumbnail, info.description);
3241 } catch (RemoteException ex) {
3242 }
3243 }
3244
3245 final void performRestartActivity(IBinder token) {
3246 ActivityRecord r = mActivities.get(token);
3247 if (r.stopped) {
3248 r.activity.performRestart();
3249 r.stopped = false;
3250 }
3251 }
3252
3253 private final void handleWindowVisibility(IBinder token, boolean show) {
3254 ActivityRecord r = mActivities.get(token);
3255 if (!show && !r.stopped) {
3256 performStopActivityInner(r, null, show);
3257 } else if (show && r.stopped) {
3258 // If we are getting ready to gc after going to the background, well
3259 // we are back active so skip it.
3260 unscheduleGcIdler();
3261
3262 r.activity.performRestart();
3263 r.stopped = false;
3264 }
3265 if (r.activity.mDecor != null) {
3266 if (Config.LOGV) Log.v(
3267 TAG, "Handle window " + r + " visibility: " + show);
3268 updateVisibility(r, show);
3269 }
3270 }
3271
3272 private final void deliverResults(ActivityRecord r, List<ResultInfo> results) {
3273 final int N = results.size();
3274 for (int i=0; i<N; i++) {
3275 ResultInfo ri = results.get(i);
3276 try {
3277 if (ri.mData != null) {
3278 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3279 }
Chris Tate8a7dc172009-03-24 20:11:42 -07003280 if (DEBUG_RESULTS) Log.v(TAG,
3281 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 r.activity.dispatchActivityResult(ri.mResultWho,
3283 ri.mRequestCode, ri.mResultCode, ri.mData);
3284 } catch (Exception e) {
3285 if (!mInstrumentation.onException(r.activity, e)) {
3286 throw new RuntimeException(
3287 "Failure delivering result " + ri + " to activity "
3288 + r.intent.getComponent().toShortString()
3289 + ": " + e.toString(), e);
3290 }
3291 }
3292 }
3293 }
3294
3295 private final void handleSendResult(ResultData res) {
3296 ActivityRecord r = mActivities.get(res.token);
Chris Tate8a7dc172009-03-24 20:11:42 -07003297 if (DEBUG_RESULTS) Log.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 if (r != null) {
3299 final boolean resumed = !r.paused;
3300 if (!r.activity.mFinished && r.activity.mDecor != null
3301 && r.hideForNow && resumed) {
3302 // We had hidden the activity because it started another
3303 // one... we have gotten a result back and we are not
3304 // paused, so make sure our window is visible.
3305 updateVisibility(r, true);
3306 }
3307 if (resumed) {
3308 try {
3309 // Now we are idle.
3310 r.activity.mCalled = false;
3311 mInstrumentation.callActivityOnPause(r.activity);
3312 if (!r.activity.mCalled) {
3313 throw new SuperNotCalledException(
3314 "Activity " + r.intent.getComponent().toShortString()
3315 + " did not call through to super.onPause()");
3316 }
3317 } catch (SuperNotCalledException e) {
3318 throw e;
3319 } catch (Exception e) {
3320 if (!mInstrumentation.onException(r.activity, e)) {
3321 throw new RuntimeException(
3322 "Unable to pause activity "
3323 + r.intent.getComponent().toShortString()
3324 + ": " + e.toString(), e);
3325 }
3326 }
3327 }
3328 deliverResults(r, res.results);
3329 if (resumed) {
3330 mInstrumentation.callActivityOnResume(r.activity);
3331 }
3332 }
3333 }
3334
3335 public final ActivityRecord performDestroyActivity(IBinder token, boolean finishing) {
3336 return performDestroyActivity(token, finishing, 0, false);
3337 }
3338
3339 private final ActivityRecord performDestroyActivity(IBinder token, boolean finishing,
3340 int configChanges, boolean getNonConfigInstance) {
3341 ActivityRecord r = mActivities.get(token);
3342 if (localLOGV) Log.v(TAG, "Performing finish of " + r);
3343 if (r != null) {
3344 r.activity.mConfigChangeFlags |= configChanges;
3345 if (finishing) {
3346 r.activity.mFinished = true;
3347 }
3348 if (!r.paused) {
3349 try {
3350 r.activity.mCalled = false;
3351 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003352 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 r.activity.getComponentName().getClassName());
3354 if (!r.activity.mCalled) {
3355 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003356 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 + " did not call through to super.onPause()");
3358 }
3359 } catch (SuperNotCalledException e) {
3360 throw e;
3361 } catch (Exception e) {
3362 if (!mInstrumentation.onException(r.activity, e)) {
3363 throw new RuntimeException(
3364 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003365 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 + ": " + e.toString(), e);
3367 }
3368 }
3369 r.paused = true;
3370 }
3371 if (!r.stopped) {
3372 try {
3373 r.activity.performStop();
3374 } catch (SuperNotCalledException e) {
3375 throw e;
3376 } catch (Exception e) {
3377 if (!mInstrumentation.onException(r.activity, e)) {
3378 throw new RuntimeException(
3379 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003380 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 + ": " + e.toString(), e);
3382 }
3383 }
3384 r.stopped = true;
3385 }
3386 if (getNonConfigInstance) {
3387 try {
3388 r.lastNonConfigurationInstance
3389 = r.activity.onRetainNonConfigurationInstance();
3390 } catch (Exception e) {
3391 if (!mInstrumentation.onException(r.activity, e)) {
3392 throw new RuntimeException(
3393 "Unable to retain activity "
3394 + r.intent.getComponent().toShortString()
3395 + ": " + e.toString(), e);
3396 }
3397 }
3398 try {
3399 r.lastNonConfigurationChildInstances
3400 = r.activity.onRetainNonConfigurationChildInstances();
3401 } catch (Exception e) {
3402 if (!mInstrumentation.onException(r.activity, e)) {
3403 throw new RuntimeException(
3404 "Unable to retain child activities "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003405 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 + ": " + e.toString(), e);
3407 }
3408 }
Bob Leee5408332009-09-04 18:31:17 -07003409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 }
3411 try {
3412 r.activity.mCalled = false;
3413 r.activity.onDestroy();
3414 if (!r.activity.mCalled) {
3415 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003416 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 " did not call through to super.onDestroy()");
3418 }
3419 if (r.window != null) {
3420 r.window.closeAllPanels();
3421 }
3422 } catch (SuperNotCalledException e) {
3423 throw e;
3424 } catch (Exception e) {
3425 if (!mInstrumentation.onException(r.activity, e)) {
3426 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003427 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3428 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 }
3430 }
3431 }
3432 mActivities.remove(token);
3433
3434 return r;
3435 }
3436
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003437 private static String safeToComponentShortString(Intent intent) {
3438 ComponentName component = intent.getComponent();
3439 return component == null ? "[Unknown]" : component.toShortString();
3440 }
3441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 private final void handleDestroyActivity(IBinder token, boolean finishing,
3443 int configChanges, boolean getNonConfigInstance) {
3444 ActivityRecord r = performDestroyActivity(token, finishing,
3445 configChanges, getNonConfigInstance);
3446 if (r != null) {
3447 WindowManager wm = r.activity.getWindowManager();
3448 View v = r.activity.mDecor;
3449 if (v != null) {
3450 if (r.activity.mVisibleFromServer) {
3451 mNumVisibleActivities--;
3452 }
3453 IBinder wtoken = v.getWindowToken();
3454 if (r.activity.mWindowAdded) {
3455 wm.removeViewImmediate(v);
3456 }
3457 if (wtoken != null) {
3458 WindowManagerImpl.getDefault().closeAll(wtoken,
3459 r.activity.getClass().getName(), "Activity");
3460 }
3461 r.activity.mDecor = null;
3462 }
3463 WindowManagerImpl.getDefault().closeAll(token,
3464 r.activity.getClass().getName(), "Activity");
3465
3466 // Mocked out contexts won't be participating in the normal
3467 // process lifecycle, but if we're running with a proper
3468 // ApplicationContext we need to have it tear down things
3469 // cleanly.
3470 Context c = r.activity.getBaseContext();
3471 if (c instanceof ApplicationContext) {
3472 ((ApplicationContext) c).scheduleFinalCleanup(
3473 r.activity.getClass().getName(), "Activity");
3474 }
3475 }
3476 if (finishing) {
3477 try {
3478 ActivityManagerNative.getDefault().activityDestroyed(token);
3479 } catch (RemoteException ex) {
3480 // If the system process has died, it's game over for everyone.
3481 }
3482 }
3483 }
3484
3485 private final void handleRelaunchActivity(ActivityRecord tmp, int configChanges) {
3486 // If we are getting ready to gc after going to the background, well
3487 // we are back active so skip it.
3488 unscheduleGcIdler();
3489
3490 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07003491
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003492 if (DEBUG_CONFIGURATION) Log.v(TAG, "Relaunching activity "
3493 + tmp.token + " with configChanges=0x"
3494 + Integer.toHexString(configChanges));
3495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 // First: make sure we have the most recent configuration and most
3497 // recent version of the activity, or skip it if some previous call
3498 // had taken a more recent version.
3499 synchronized (mRelaunchingActivities) {
3500 int N = mRelaunchingActivities.size();
3501 IBinder token = tmp.token;
3502 tmp = null;
3503 for (int i=0; i<N; i++) {
3504 ActivityRecord r = mRelaunchingActivities.get(i);
3505 if (r.token == token) {
3506 tmp = r;
3507 mRelaunchingActivities.remove(i);
3508 i--;
3509 N--;
3510 }
3511 }
Bob Leee5408332009-09-04 18:31:17 -07003512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 if (tmp == null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003514 if (DEBUG_CONFIGURATION) Log.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 return;
3516 }
Bob Leee5408332009-09-04 18:31:17 -07003517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 if (mPendingConfiguration != null) {
3519 changedConfig = mPendingConfiguration;
3520 mPendingConfiguration = null;
3521 }
3522 }
Bob Leee5408332009-09-04 18:31:17 -07003523
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003524 if (DEBUG_CONFIGURATION) Log.v(TAG, "Relaunching activity "
3525 + tmp.token + ": changedConfig=" + changedConfig);
3526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 // If there was a pending configuration change, execute it first.
3528 if (changedConfig != null) {
3529 handleConfigurationChanged(changedConfig);
3530 }
Bob Leee5408332009-09-04 18:31:17 -07003531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 ActivityRecord r = mActivities.get(tmp.token);
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003533 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 if (r == null) {
3535 return;
3536 }
Bob Leee5408332009-09-04 18:31:17 -07003537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003539 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 Bundle savedState = null;
3542 if (!r.paused) {
3543 savedState = performPauseActivity(r.token, false, true);
3544 }
Bob Leee5408332009-09-04 18:31:17 -07003545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 r.activity = null;
3549 r.window = null;
3550 r.hideForNow = false;
3551 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003552 // Merge any pending results and pending intents; don't just replace them
3553 if (tmp.pendingResults != null) {
3554 if (r.pendingResults == null) {
3555 r.pendingResults = tmp.pendingResults;
3556 } else {
3557 r.pendingResults.addAll(tmp.pendingResults);
3558 }
3559 }
3560 if (tmp.pendingIntents != null) {
3561 if (r.pendingIntents == null) {
3562 r.pendingIntents = tmp.pendingIntents;
3563 } else {
3564 r.pendingIntents.addAll(tmp.pendingIntents);
3565 }
3566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 r.startsNotResumed = tmp.startsNotResumed;
3568 if (savedState != null) {
3569 r.state = savedState;
3570 }
Bob Leee5408332009-09-04 18:31:17 -07003571
Christopher Tateb70f3df2009-04-07 16:07:59 -07003572 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 }
3574
3575 private final void handleRequestThumbnail(IBinder token) {
3576 ActivityRecord r = mActivities.get(token);
3577 Bitmap thumbnail = createThumbnailBitmap(r);
3578 CharSequence description = null;
3579 try {
3580 description = r.activity.onCreateDescription();
3581 } catch (Exception e) {
3582 if (!mInstrumentation.onException(r.activity, e)) {
3583 throw new RuntimeException(
3584 "Unable to create description of activity "
3585 + r.intent.getComponent().toShortString()
3586 + ": " + e.toString(), e);
3587 }
3588 }
3589 //System.out.println("Reporting top thumbnail " + thumbnail);
3590 try {
3591 ActivityManagerNative.getDefault().reportThumbnail(
3592 token, thumbnail, description);
3593 } catch (RemoteException ex) {
3594 }
3595 }
3596
3597 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
3598 boolean allActivities, Configuration newConfig) {
3599 ArrayList<ComponentCallbacks> callbacks
3600 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 if (mActivities.size() > 0) {
3603 Iterator<ActivityRecord> it = mActivities.values().iterator();
3604 while (it.hasNext()) {
3605 ActivityRecord ar = it.next();
3606 Activity a = ar.activity;
3607 if (a != null) {
3608 if (!ar.activity.mFinished && (allActivities ||
3609 (a != null && !ar.paused))) {
3610 // If the activity is currently resumed, its configuration
3611 // needs to change right now.
3612 callbacks.add(a);
3613 } else if (newConfig != null) {
3614 // Otherwise, we will tell it about the change
3615 // the next time it is resumed or shown. Note that
3616 // the activity manager may, before then, decide the
3617 // activity needs to be destroyed to handle its new
3618 // configuration.
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003619 if (DEBUG_CONFIGURATION) Log.v(TAG, "Setting activity "
3620 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 ar.newConfig = newConfig;
3622 }
3623 }
3624 }
3625 }
3626 if (mServices.size() > 0) {
3627 Iterator<Service> it = mServices.values().iterator();
3628 while (it.hasNext()) {
3629 callbacks.add(it.next());
3630 }
3631 }
3632 synchronized (mProviderMap) {
3633 if (mLocalProviders.size() > 0) {
3634 Iterator<ProviderRecord> it = mLocalProviders.values().iterator();
3635 while (it.hasNext()) {
3636 callbacks.add(it.next().mLocalProvider);
3637 }
3638 }
3639 }
3640 final int N = mAllApplications.size();
3641 for (int i=0; i<N; i++) {
3642 callbacks.add(mAllApplications.get(i));
3643 }
Bob Leee5408332009-09-04 18:31:17 -07003644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 return callbacks;
3646 }
Bob Leee5408332009-09-04 18:31:17 -07003647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 private final void performConfigurationChanged(
3649 ComponentCallbacks cb, Configuration config) {
3650 // Only for Activity objects, check that they actually call up to their
3651 // superclass implementation. ComponentCallbacks is an interface, so
3652 // we check the runtime type and act accordingly.
3653 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3654 if (activity != null) {
3655 activity.mCalled = false;
3656 }
Bob Leee5408332009-09-04 18:31:17 -07003657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 boolean shouldChangeConfig = false;
3659 if ((activity == null) || (activity.mCurrentConfig == null)) {
3660 shouldChangeConfig = true;
3661 } else {
Bob Leee5408332009-09-04 18:31:17 -07003662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 // If the new config is the same as the config this Activity
3664 // is already running with then don't bother calling
3665 // onConfigurationChanged
3666 int diff = activity.mCurrentConfig.diff(config);
3667 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07003668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 // If this activity doesn't handle any of the config changes
3670 // then don't bother calling onConfigurationChanged as we're
3671 // going to destroy it.
3672 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
3673 shouldChangeConfig = true;
3674 }
3675 }
3676 }
Bob Leee5408332009-09-04 18:31:17 -07003677
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003678 if (DEBUG_CONFIGURATION) Log.v(TAG, "Config callback " + cb
3679 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 if (shouldChangeConfig) {
3681 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 if (activity != null) {
3684 if (!activity.mCalled) {
3685 throw new SuperNotCalledException(
3686 "Activity " + activity.getLocalClassName() +
3687 " did not call through to super.onConfigurationChanged()");
3688 }
3689 activity.mConfigChangeFlags = 0;
3690 activity.mCurrentConfig = new Configuration(config);
3691 }
3692 }
3693 }
3694
3695 final void handleConfigurationChanged(Configuration config) {
Bob Leee5408332009-09-04 18:31:17 -07003696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 synchronized (mRelaunchingActivities) {
3698 if (mPendingConfiguration != null) {
3699 config = mPendingConfiguration;
3700 mPendingConfiguration = null;
3701 }
3702 }
Bob Leee5408332009-09-04 18:31:17 -07003703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 ArrayList<ComponentCallbacks> callbacks
3705 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003706
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003707 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handle configuration changed: "
3708 + config);
3709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 synchronized(mPackages) {
3711 if (mConfiguration == null) {
3712 mConfiguration = new Configuration();
3713 }
3714 mConfiguration.updateFrom(config);
3715 DisplayMetrics dm = getDisplayMetricsLocked(true);
3716
3717 // set it for java, this also affects newly created Resources
3718 if (config.locale != null) {
3719 Locale.setDefault(config.locale);
3720 }
3721
Dianne Hackborn0d907fa2009-07-27 20:48:50 -07003722 Resources.updateSystemConfiguration(config, dm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723
3724 ApplicationContext.ApplicationPackageManager.configurationChanged();
3725 //Log.i(TAG, "Configuration changed in " + currentPackageName());
3726 {
3727 Iterator<WeakReference<Resources>> it =
3728 mActiveResources.values().iterator();
3729 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3730 // mActiveResources.entrySet().iterator();
3731 while (it.hasNext()) {
3732 WeakReference<Resources> v = it.next();
3733 Resources r = v.get();
3734 if (r != null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003735 r.updateConfiguration(config, dm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 //Log.i(TAG, "Updated app resources " + v.getKey()
3737 // + " " + r + ": " + r.getConfiguration());
3738 } else {
3739 //Log.i(TAG, "Removing old resources " + v.getKey());
3740 it.remove();
3741 }
3742 }
3743 }
Bob Leee5408332009-09-04 18:31:17 -07003744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 callbacks = collectComponentCallbacksLocked(false, config);
3746 }
Bob Leee5408332009-09-04 18:31:17 -07003747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 final int N = callbacks.size();
3749 for (int i=0; i<N; i++) {
3750 performConfigurationChanged(callbacks.get(i), config);
3751 }
3752 }
3753
3754 final void handleActivityConfigurationChanged(IBinder token) {
3755 ActivityRecord r = mActivities.get(token);
3756 if (r == null || r.activity == null) {
3757 return;
3758 }
Bob Leee5408332009-09-04 18:31:17 -07003759
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003760 if (DEBUG_CONFIGURATION) Log.v(TAG, "Handle activity config changed: "
3761 + r.activityInfo.name);
3762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 performConfigurationChanged(r.activity, mConfiguration);
3764 }
3765
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003766 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003767 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003768 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003769 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3770 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003771 } catch (RuntimeException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003772 Log.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003773 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003774 } finally {
3775 try {
3776 pcd.fd.close();
3777 } catch (IOException e) {
3778 Log.w(TAG, "Failure closing profile fd", e);
3779 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003780 }
3781 } else {
3782 Debug.stopMethodTracing();
3783 }
3784 }
Bob Leee5408332009-09-04 18:31:17 -07003785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 final void handleLowMemory() {
3787 ArrayList<ComponentCallbacks> callbacks
3788 = new ArrayList<ComponentCallbacks>();
3789
3790 synchronized(mPackages) {
3791 callbacks = collectComponentCallbacksLocked(true, null);
3792 }
Bob Leee5408332009-09-04 18:31:17 -07003793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 final int N = callbacks.size();
3795 for (int i=0; i<N; i++) {
3796 callbacks.get(i).onLowMemory();
3797 }
3798
Chris Tatece229052009-03-25 16:44:52 -07003799 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3800 if (Process.myUid() != Process.SYSTEM_UID) {
3801 int sqliteReleased = SQLiteDatabase.releaseMemory();
3802 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3803 }
Bob Leee5408332009-09-04 18:31:17 -07003804
Mike Reedcaf0df12009-04-27 14:32:05 -04003805 // Ask graphics to free up as much as possible (font/image caches)
3806 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807
3808 BinderInternal.forceGc("mem");
3809 }
3810
3811 private final void handleBindApplication(AppBindData data) {
3812 mBoundApplication = data;
3813 mConfiguration = new Configuration(data.config);
3814
3815 // We now rely on this being set by zygote.
3816 //Process.setGid(data.appInfo.gid);
3817 //Process.setUid(data.appInfo.uid);
3818
3819 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003820 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 android.ddm.DdmHandleAppName.setAppName(data.processName);
3822
3823 /*
3824 * Before spawning a new process, reset the time zone to be the system time zone.
3825 * This needs to be done because the system time zone could have changed after the
3826 * the spawning of this process. Without doing this this process would have the incorrect
3827 * system time zone.
3828 */
3829 TimeZone.setDefault(null);
3830
3831 /*
3832 * Initialize the default locale in this process for the reasons we set the time zone.
3833 */
3834 Locale.setDefault(data.config.locale);
3835
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003836 /*
3837 * Update the system configuration since its preloaded and might not
3838 * reflect configuration changes. The configuration object passed
3839 * in AppBindData can be safely assumed to be up to date
3840 */
3841 Resources.getSystem().updateConfiguration(mConfiguration, null);
3842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 data.info = getPackageInfoNoCheck(data.appInfo);
3844
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003845 /**
3846 * Switch this process to density compatibility mode if needed.
3847 */
3848 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3849 == 0) {
3850 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3851 }
Bob Leee5408332009-09-04 18:31:17 -07003852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3854 // XXX should have option to change the port.
3855 Debug.changeDebugPort(8100);
3856 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
3857 Log.w(TAG, "Application " + data.info.getPackageName()
3858 + " is waiting for the debugger on port 8100...");
3859
3860 IActivityManager mgr = ActivityManagerNative.getDefault();
3861 try {
3862 mgr.showWaitingForDebugger(mAppThread, true);
3863 } catch (RemoteException ex) {
3864 }
3865
3866 Debug.waitForDebugger();
3867
3868 try {
3869 mgr.showWaitingForDebugger(mAppThread, false);
3870 } catch (RemoteException ex) {
3871 }
3872
3873 } else {
3874 Log.w(TAG, "Application " + data.info.getPackageName()
3875 + " can be debugged on port 8100...");
3876 }
3877 }
3878
3879 if (data.instrumentationName != null) {
3880 ApplicationContext appContext = new ApplicationContext();
3881 appContext.init(data.info, null, this);
3882 InstrumentationInfo ii = null;
3883 try {
3884 ii = appContext.getPackageManager().
3885 getInstrumentationInfo(data.instrumentationName, 0);
3886 } catch (PackageManager.NameNotFoundException e) {
3887 }
3888 if (ii == null) {
3889 throw new RuntimeException(
3890 "Unable to find instrumentation info for: "
3891 + data.instrumentationName);
3892 }
3893
3894 mInstrumentationAppDir = ii.sourceDir;
3895 mInstrumentationAppPackage = ii.packageName;
3896 mInstrumentedAppDir = data.info.getAppDir();
3897
3898 ApplicationInfo instrApp = new ApplicationInfo();
3899 instrApp.packageName = ii.packageName;
3900 instrApp.sourceDir = ii.sourceDir;
3901 instrApp.publicSourceDir = ii.publicSourceDir;
3902 instrApp.dataDir = ii.dataDir;
3903 PackageInfo pi = getPackageInfo(instrApp,
3904 appContext.getClassLoader(), false, true);
3905 ApplicationContext instrContext = new ApplicationContext();
3906 instrContext.init(pi, null, this);
3907
3908 try {
3909 java.lang.ClassLoader cl = instrContext.getClassLoader();
3910 mInstrumentation = (Instrumentation)
3911 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3912 } catch (Exception e) {
3913 throw new RuntimeException(
3914 "Unable to instantiate instrumentation "
3915 + data.instrumentationName + ": " + e.toString(), e);
3916 }
3917
3918 mInstrumentation.init(this, instrContext, appContext,
3919 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3920
3921 if (data.profileFile != null && !ii.handleProfiling) {
3922 data.handlingProfiling = true;
3923 File file = new File(data.profileFile);
3924 file.getParentFile().mkdirs();
3925 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3926 }
3927
3928 try {
3929 mInstrumentation.onCreate(data.instrumentationArgs);
3930 }
3931 catch (Exception e) {
3932 throw new RuntimeException(
3933 "Exception thrown in onCreate() of "
3934 + data.instrumentationName + ": " + e.toString(), e);
3935 }
3936
3937 } else {
3938 mInstrumentation = new Instrumentation();
3939 }
3940
Christopher Tate181fafa2009-05-14 11:12:14 -07003941 // If the app is being launched for full backup or restore, bring it up in
3942 // a restricted environment with the base application class.
3943 Application app = data.info.makeApplication(data.restrictedBackupMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 mInitialApplication = app;
3945
3946 List<ProviderInfo> providers = data.providers;
3947 if (providers != null) {
3948 installContentProviders(app, providers);
3949 }
3950
3951 try {
3952 mInstrumentation.callApplicationOnCreate(app);
3953 } catch (Exception e) {
3954 if (!mInstrumentation.onException(app, e)) {
3955 throw new RuntimeException(
3956 "Unable to create application " + app.getClass().getName()
3957 + ": " + e.toString(), e);
3958 }
3959 }
3960 }
3961
3962 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3963 IActivityManager am = ActivityManagerNative.getDefault();
3964 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3965 Debug.stopMethodTracing();
3966 }
3967 //Log.i(TAG, "am: " + ActivityManagerNative.getDefault()
3968 // + ", app thr: " + mAppThread);
3969 try {
3970 am.finishInstrumentation(mAppThread, resultCode, results);
3971 } catch (RemoteException ex) {
3972 }
3973 }
3974
3975 private final void installContentProviders(
3976 Context context, List<ProviderInfo> providers) {
3977 final ArrayList<IActivityManager.ContentProviderHolder> results =
3978 new ArrayList<IActivityManager.ContentProviderHolder>();
3979
3980 Iterator<ProviderInfo> i = providers.iterator();
3981 while (i.hasNext()) {
3982 ProviderInfo cpi = i.next();
3983 StringBuilder buf = new StringBuilder(128);
3984 buf.append("Publishing provider ");
3985 buf.append(cpi.authority);
3986 buf.append(": ");
3987 buf.append(cpi.name);
3988 Log.i(TAG, buf.toString());
3989 IContentProvider cp = installProvider(context, null, cpi, false);
3990 if (cp != null) {
3991 IActivityManager.ContentProviderHolder cph =
3992 new IActivityManager.ContentProviderHolder(cpi);
3993 cph.provider = cp;
3994 results.add(cph);
3995 // Don't ever unload this provider from the process.
3996 synchronized(mProviderMap) {
3997 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3998 }
3999 }
4000 }
4001
4002 try {
4003 ActivityManagerNative.getDefault().publishContentProviders(
4004 getApplicationThread(), results);
4005 } catch (RemoteException ex) {
4006 }
4007 }
4008
4009 private final IContentProvider getProvider(Context context, String name) {
4010 synchronized(mProviderMap) {
4011 final ProviderRecord pr = mProviderMap.get(name);
4012 if (pr != null) {
4013 return pr.mProvider;
4014 }
4015 }
4016
4017 IActivityManager.ContentProviderHolder holder = null;
4018 try {
4019 holder = ActivityManagerNative.getDefault().getContentProvider(
4020 getApplicationThread(), name);
4021 } catch (RemoteException ex) {
4022 }
4023 if (holder == null) {
4024 Log.e(TAG, "Failed to find provider info for " + name);
4025 return null;
4026 }
4027 if (holder.permissionFailure != null) {
4028 throw new SecurityException("Permission " + holder.permissionFailure
4029 + " required for provider " + name);
4030 }
4031
4032 IContentProvider prov = installProvider(context, holder.provider,
4033 holder.info, true);
4034 //Log.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
4035 if (holder.noReleaseNeeded || holder.provider == null) {
4036 // We are not going to release the provider if it is an external
4037 // provider that doesn't care about being released, or if it is
4038 // a local provider running in this process.
4039 //Log.i(TAG, "*** NO RELEASE NEEDED");
4040 synchronized(mProviderMap) {
4041 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
4042 }
4043 }
4044 return prov;
4045 }
4046
4047 public final IContentProvider acquireProvider(Context c, String name) {
4048 IContentProvider provider = getProvider(c, name);
4049 if(provider == null)
4050 return null;
4051 IBinder jBinder = provider.asBinder();
4052 synchronized(mProviderMap) {
4053 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4054 if(prc == null) {
4055 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4056 } else {
4057 prc.count++;
4058 } //end else
4059 } //end synchronized
4060 return provider;
4061 }
4062
4063 public final boolean releaseProvider(IContentProvider provider) {
4064 if(provider == null) {
4065 return false;
4066 }
4067 IBinder jBinder = provider.asBinder();
4068 synchronized(mProviderMap) {
4069 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4070 if(prc == null) {
4071 if(localLOGV) Log.v(TAG, "releaseProvider::Weird shouldnt be here");
4072 return false;
4073 } else {
4074 prc.count--;
4075 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004076 // Schedule the actual remove asynchronously, since we
4077 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004078 // TODO: it would be nice to post a delayed message, so
4079 // if we come back and need the same provider quickly
4080 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004081 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4082 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 } //end if
4084 } //end else
4085 } //end synchronized
4086 return true;
4087 }
4088
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004089 final void completeRemoveProvider(IContentProvider provider) {
4090 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004091 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004092 synchronized(mProviderMap) {
4093 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4094 if(prc != null && prc.count == 0) {
4095 mProviderRefCountMap.remove(jBinder);
4096 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004097 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004098 }
4099 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004100
4101 if (name != null) {
4102 try {
4103 if(localLOGV) Log.v(TAG, "removeProvider::Invoking " +
4104 "ActivityManagerNative.removeContentProvider(" + name);
4105 ActivityManagerNative.getDefault().removeContentProvider(
4106 getApplicationThread(), name);
4107 } catch (RemoteException e) {
4108 //do nothing content provider object is dead any way
4109 } //end catch
4110 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004111 }
4112
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004113 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004115 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 }
4117 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004119 String name = null;
4120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 // remove the provider from mProviderMap
4122 Iterator<ProviderRecord> iter = mProviderMap.values().iterator();
4123 while (iter.hasNext()) {
4124 ProviderRecord pr = iter.next();
4125 IBinder myBinder = pr.mProvider.asBinder();
4126 if (myBinder == providerBinder) {
4127 //find if its published by this process itself
4128 if(pr.mLocalProvider != null) {
4129 if(localLOGV) Log.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004130 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 }
4132 if(localLOGV) Log.v(TAG, "removeProvider::Not local provider Unlinking " +
4133 "death recipient");
4134 //content provider is in another process
4135 myBinder.unlinkToDeath(pr, 0);
4136 iter.remove();
4137 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004138 if(name == null) {
4139 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 }
4141 } //end if myBinder
4142 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004143
4144 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 }
4146
4147 final void removeDeadProvider(String name, IContentProvider provider) {
4148 synchronized(mProviderMap) {
4149 ProviderRecord pr = mProviderMap.get(name);
4150 if (pr.mProvider.asBinder() == provider.asBinder()) {
4151 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004152 ProviderRecord removed = mProviderMap.remove(name);
4153 if (removed != null) {
4154 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 }
4157 }
4158 }
4159
4160 final void removeDeadProviderLocked(String name, IContentProvider provider) {
4161 ProviderRecord pr = mProviderMap.get(name);
4162 if (pr.mProvider.asBinder() == provider.asBinder()) {
4163 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004164 ProviderRecord removed = mProviderMap.remove(name);
4165 if (removed != null) {
4166 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 }
4169 }
4170
4171 private final IContentProvider installProvider(Context context,
4172 IContentProvider provider, ProviderInfo info, boolean noisy) {
4173 ContentProvider localProvider = null;
4174 if (provider == null) {
4175 if (noisy) {
4176 Log.d(TAG, "Loading provider " + info.authority + ": "
4177 + info.name);
4178 }
4179 Context c = null;
4180 ApplicationInfo ai = info.applicationInfo;
4181 if (context.getPackageName().equals(ai.packageName)) {
4182 c = context;
4183 } else if (mInitialApplication != null &&
4184 mInitialApplication.getPackageName().equals(ai.packageName)) {
4185 c = mInitialApplication;
4186 } else {
4187 try {
4188 c = context.createPackageContext(ai.packageName,
4189 Context.CONTEXT_INCLUDE_CODE);
4190 } catch (PackageManager.NameNotFoundException e) {
4191 }
4192 }
4193 if (c == null) {
4194 Log.w(TAG, "Unable to get context for package " +
4195 ai.packageName +
4196 " while loading content provider " +
4197 info.name);
4198 return null;
4199 }
4200 try {
4201 final java.lang.ClassLoader cl = c.getClassLoader();
4202 localProvider = (ContentProvider)cl.
4203 loadClass(info.name).newInstance();
4204 provider = localProvider.getIContentProvider();
4205 if (provider == null) {
4206 Log.e(TAG, "Failed to instantiate class " +
4207 info.name + " from sourceDir " +
4208 info.applicationInfo.sourceDir);
4209 return null;
4210 }
4211 if (Config.LOGV) Log.v(
4212 TAG, "Instantiating local provider " + info.name);
4213 // XXX Need to create the correct context for this provider.
4214 localProvider.attachInfo(c, info);
4215 } catch (java.lang.Exception e) {
4216 if (!mInstrumentation.onException(null, e)) {
4217 throw new RuntimeException(
4218 "Unable to get provider " + info.name
4219 + ": " + e.toString(), e);
4220 }
4221 return null;
4222 }
4223 } else if (localLOGV) {
4224 Log.v(TAG, "Installing external provider " + info.authority + ": "
4225 + info.name);
4226 }
4227
4228 synchronized (mProviderMap) {
4229 // Cache the pointer for the remote provider.
4230 String names[] = PATTERN_SEMICOLON.split(info.authority);
4231 for (int i=0; i<names.length; i++) {
4232 ProviderRecord pr = new ProviderRecord(names[i], provider,
4233 localProvider);
4234 try {
4235 provider.asBinder().linkToDeath(pr, 0);
4236 mProviderMap.put(names[i], pr);
4237 } catch (RemoteException e) {
4238 return null;
4239 }
4240 }
4241 if (localProvider != null) {
4242 mLocalProviders.put(provider.asBinder(),
4243 new ProviderRecord(null, provider, localProvider));
4244 }
4245 }
4246
4247 return provider;
4248 }
4249
4250 private final void attach(boolean system) {
4251 sThreadLocal.set(this);
4252 mSystemThread = system;
4253 AndroidHttpClient.setThreadBlocked(true);
4254 if (!system) {
4255 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4256 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4257 IActivityManager mgr = ActivityManagerNative.getDefault();
4258 try {
4259 mgr.attachApplication(mAppThread);
4260 } catch (RemoteException ex) {
4261 }
4262 } else {
4263 // Don't set application object here -- if the system crashes,
4264 // we can't display an alert, we just want to die die die.
4265 android.ddm.DdmHandleAppName.setAppName("system_process");
4266 try {
4267 mInstrumentation = new Instrumentation();
4268 ApplicationContext context = new ApplicationContext();
4269 context.init(getSystemContext().mPackageInfo, null, this);
4270 Application app = Instrumentation.newApplication(Application.class, context);
4271 mAllApplications.add(app);
4272 mInitialApplication = app;
4273 app.onCreate();
4274 } catch (Exception e) {
4275 throw new RuntimeException(
4276 "Unable to instantiate Application():" + e.toString(), e);
4277 }
4278 }
4279 }
4280
4281 private final void detach()
4282 {
4283 AndroidHttpClient.setThreadBlocked(false);
4284 sThreadLocal.set(null);
4285 }
4286
4287 public static final ActivityThread systemMain() {
4288 ActivityThread thread = new ActivityThread();
4289 thread.attach(true);
4290 return thread;
4291 }
4292
4293 public final void installSystemProviders(List providers) {
4294 if (providers != null) {
4295 installContentProviders(mInitialApplication,
4296 (List<ProviderInfo>)providers);
4297 }
4298 }
4299
4300 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004301 SamplingProfilerIntegration.start();
4302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 Process.setArgV0("<pre-initialized>");
4304
4305 Looper.prepareMainLooper();
4306
4307 ActivityThread thread = new ActivityThread();
4308 thread.attach(false);
4309
4310 Looper.loop();
4311
4312 if (Process.supportsProcesses()) {
4313 throw new RuntimeException("Main thread loop unexpectedly exited");
4314 }
4315
4316 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02004317 String name = (thread.mInitialApplication != null)
4318 ? thread.mInitialApplication.getPackageName()
4319 : "<unknown>";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 Log.i(TAG, "Main thread of " + name + " is now exiting");
4321 }
4322}