blob: 76a133b65a03f9f5c0e071d956b6947c40aec3a9 [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 Tate181fafa2009-05-14 11:12:14 -0700125 private static final boolean DEBUG_BACKUP = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
127 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
128 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
129 private static final int LOG_ON_PAUSE_CALLED = 30021;
130 private static final int LOG_ON_RESUME_CALLED = 30022;
131
Bob Leee5408332009-09-04 18:31:17 -0700132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 public static final ActivityThread currentActivityThread() {
134 return (ActivityThread)sThreadLocal.get();
135 }
136
137 public static final String currentPackageName()
138 {
139 ActivityThread am = currentActivityThread();
140 return (am != null && am.mBoundApplication != null)
141 ? am.mBoundApplication.processName : null;
142 }
143
144 public static IPackageManager getPackageManager() {
145 if (sPackageManager != null) {
146 //Log.v("PackageManager", "returning cur default = " + sPackageManager);
147 return sPackageManager;
148 }
149 IBinder b = ServiceManager.getService("package");
150 //Log.v("PackageManager", "default service binder = " + b);
151 sPackageManager = IPackageManager.Stub.asInterface(b);
152 //Log.v("PackageManager", "default service = " + sPackageManager);
153 return sPackageManager;
154 }
155
156 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
157 if (mDisplayMetrics != null && !forceUpdate) {
158 return mDisplayMetrics;
159 }
160 if (mDisplay == null) {
161 WindowManager wm = WindowManagerImpl.getDefault();
162 mDisplay = wm.getDefaultDisplay();
163 }
164 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
165 mDisplay.getMetrics(metrics);
166 //Log.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
167 // + metrics.heightPixels + " den=" + metrics.density
168 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
169 return metrics;
170 }
171
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700172 /**
173 * Creates the top level Resources for applications with the given compatibility info.
174 *
175 * @param resDir the resource directory.
176 * @param compInfo the compability info. It will use the default compatibility info when it's
177 * null.
178 */
179 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 synchronized (mPackages) {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700181 // Resources is app scale dependent.
182 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700183 if (false) {
184 Log.w(TAG, "getTopLevelResources: " + resDir + " / "
185 + compInfo.applicationScale);
186 }
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700187 WeakReference<Resources> wr = mActiveResources.get(key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 Resources r = wr != null ? wr.get() : null;
189 if (r != null && r.getAssets().isUpToDate()) {
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700190 if (false) {
191 Log.w(TAG, "Returning cached resources " + r + " " + resDir
192 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 return r;
195 }
196
197 //if (r != null) {
198 // Log.w(TAG, "Throwing away out-of-date resources!!!! "
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700199 // + r + " " + resDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 //}
201
202 AssetManager assets = new AssetManager();
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700203 if (assets.addAssetPath(resDir) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 return null;
205 }
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700206
207 //Log.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700208 DisplayMetrics metrics = getDisplayMetricsLocked(false);
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700209 r = new Resources(assets, metrics, getConfiguration(), compInfo);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700210 if (false) {
211 Log.i(TAG, "Created app resources " + resDir + " " + r + ": "
212 + r.getConfiguration() + " appScale="
213 + r.getCompatibilityInfo().applicationScale);
214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 // XXX need to remove entries when weak references go away
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700216 mActiveResources.put(key, new WeakReference<Resources>(r));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 return r;
218 }
219 }
220
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700221 /**
222 * Creates the top level resources for the given package.
223 */
224 Resources getTopLevelResources(String resDir, PackageInfo pkgInfo) {
225 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
226 }
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 final Handler getHandler() {
229 return mH;
230 }
231
232 public final static class PackageInfo {
233
234 private final ActivityThread mActivityThread;
235 private final ApplicationInfo mApplicationInfo;
236 private final String mPackageName;
237 private final String mAppDir;
238 private final String mResDir;
239 private final String[] mSharedLibraries;
240 private final String mDataDir;
241 private final File mDataDirFile;
242 private final ClassLoader mBaseClassLoader;
243 private final boolean mSecurityViolation;
244 private final boolean mIncludeCode;
245 private Resources mResources;
246 private ClassLoader mClassLoader;
247 private Application mApplication;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700248 private CompatibilityInfo mCompatibilityInfo;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mReceivers
251 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
252 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mUnregisteredReceivers
253 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>();
254 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mServices
255 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
256 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mUnboundServices
257 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>();
258
259 int mClientCount = 0;
260
261 public PackageInfo(ActivityThread activityThread, ApplicationInfo aInfo,
262 ActivityThread mainThread, ClassLoader baseLoader,
263 boolean securityViolation, boolean includeCode) {
264 mActivityThread = activityThread;
265 mApplicationInfo = aInfo;
266 mPackageName = aInfo.packageName;
267 mAppDir = aInfo.sourceDir;
268 mResDir = aInfo.uid == Process.myUid() ? aInfo.sourceDir
269 : aInfo.publicSourceDir;
270 mSharedLibraries = aInfo.sharedLibraryFiles;
271 mDataDir = aInfo.dataDir;
272 mDataDirFile = mDataDir != null ? new File(mDataDir) : null;
273 mBaseClassLoader = baseLoader;
274 mSecurityViolation = securityViolation;
275 mIncludeCode = includeCode;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700276 mCompatibilityInfo = new CompatibilityInfo(aInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277
278 if (mAppDir == null) {
279 if (mSystemContext == null) {
280 mSystemContext =
281 ApplicationContext.createSystemContext(mainThread);
282 mSystemContext.getResources().updateConfiguration(
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700283 mainThread.getConfiguration(),
284 mainThread.getDisplayMetricsLocked(false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 //Log.i(TAG, "Created system resources "
286 // + mSystemContext.getResources() + ": "
287 // + mSystemContext.getResources().getConfiguration());
288 }
289 mClassLoader = mSystemContext.getClassLoader();
290 mResources = mSystemContext.getResources();
291 }
292 }
293
294 public PackageInfo(ActivityThread activityThread, String name,
Mike Cleron432b7132009-09-24 15:28:29 -0700295 Context systemContext, ApplicationInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 mActivityThread = activityThread;
Mike Cleron432b7132009-09-24 15:28:29 -0700297 mApplicationInfo = info != null ? info : new ApplicationInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 mApplicationInfo.packageName = name;
299 mPackageName = name;
300 mAppDir = null;
301 mResDir = null;
302 mSharedLibraries = null;
303 mDataDir = null;
304 mDataDirFile = null;
305 mBaseClassLoader = null;
306 mSecurityViolation = false;
307 mIncludeCode = true;
308 mClassLoader = systemContext.getClassLoader();
309 mResources = systemContext.getResources();
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700310 mCompatibilityInfo = new CompatibilityInfo(mApplicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 }
312
313 public String getPackageName() {
314 return mPackageName;
315 }
316
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700317 public ApplicationInfo getApplicationInfo() {
318 return mApplicationInfo;
319 }
Bob Leee5408332009-09-04 18:31:17 -0700320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 public boolean isSecurityViolation() {
322 return mSecurityViolation;
323 }
324
325 /**
326 * Gets the array of shared libraries that are listed as
327 * used by the given package.
Bob Leee5408332009-09-04 18:31:17 -0700328 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 * @param packageName the name of the package (note: not its
330 * file name)
331 * @return null-ok; the array of shared libraries, each one
332 * a fully-qualified path
333 */
334 private static String[] getLibrariesFor(String packageName) {
335 ApplicationInfo ai = null;
336 try {
337 ai = getPackageManager().getApplicationInfo(packageName,
338 PackageManager.GET_SHARED_LIBRARY_FILES);
339 } catch (RemoteException e) {
340 throw new AssertionError(e);
341 }
342
343 if (ai == null) {
344 return null;
345 }
346
347 return ai.sharedLibraryFiles;
348 }
349
350 /**
351 * Combines two arrays (of library names) such that they are
352 * concatenated in order but are devoid of duplicates. The
353 * result is a single string with the names of the libraries
354 * separated by colons, or <code>null</code> if both lists
355 * were <code>null</code> or empty.
Bob Leee5408332009-09-04 18:31:17 -0700356 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 * @param list1 null-ok; the first list
358 * @param list2 null-ok; the second list
359 * @return null-ok; the combination
360 */
361 private static String combineLibs(String[] list1, String[] list2) {
362 StringBuilder result = new StringBuilder(300);
363 boolean first = true;
364
365 if (list1 != null) {
366 for (String s : list1) {
367 if (first) {
368 first = false;
369 } else {
370 result.append(':');
371 }
372 result.append(s);
373 }
374 }
375
376 // Only need to check for duplicates if list1 was non-empty.
377 boolean dupCheck = !first;
378
379 if (list2 != null) {
380 for (String s : list2) {
381 if (dupCheck && ArrayUtils.contains(list1, s)) {
382 continue;
383 }
Bob Leee5408332009-09-04 18:31:17 -0700384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 if (first) {
386 first = false;
387 } else {
388 result.append(':');
389 }
390 result.append(s);
391 }
392 }
393
394 return result.toString();
395 }
Bob Leee5408332009-09-04 18:31:17 -0700396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 public ClassLoader getClassLoader() {
398 synchronized (this) {
399 if (mClassLoader != null) {
400 return mClassLoader;
401 }
402
403 if (mIncludeCode && !mPackageName.equals("android")) {
404 String zip = mAppDir;
405
406 /*
407 * The following is a bit of a hack to inject
408 * instrumentation into the system: If the app
409 * being started matches one of the instrumentation names,
410 * then we combine both the "instrumentation" and
411 * "instrumented" app into the path, along with the
412 * concatenation of both apps' shared library lists.
413 */
414
415 String instrumentationAppDir =
416 mActivityThread.mInstrumentationAppDir;
417 String instrumentationAppPackage =
418 mActivityThread.mInstrumentationAppPackage;
419 String instrumentedAppDir =
420 mActivityThread.mInstrumentedAppDir;
421 String[] instrumentationLibs = null;
422
423 if (mAppDir.equals(instrumentationAppDir)
424 || mAppDir.equals(instrumentedAppDir)) {
425 zip = instrumentationAppDir + ":" + instrumentedAppDir;
426 if (! instrumentedAppDir.equals(instrumentationAppDir)) {
427 instrumentationLibs =
428 getLibrariesFor(instrumentationAppPackage);
429 }
430 }
431
432 if ((mSharedLibraries != null) ||
433 (instrumentationLibs != null)) {
Bob Leee5408332009-09-04 18:31:17 -0700434 zip =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 combineLibs(mSharedLibraries, instrumentationLibs)
436 + ':' + zip;
437 }
438
439 /*
440 * With all the combination done (if necessary, actually
441 * create the class loader.
442 */
443
444 if (localLOGV) Log.v(TAG, "Class path: " + zip);
445
446 mClassLoader =
447 ApplicationLoaders.getDefault().getClassLoader(
448 zip, mDataDir, mBaseClassLoader);
449 } else {
450 if (mBaseClassLoader == null) {
451 mClassLoader = ClassLoader.getSystemClassLoader();
452 } else {
453 mClassLoader = mBaseClassLoader;
454 }
455 }
456 return mClassLoader;
457 }
458 }
459
460 public String getAppDir() {
461 return mAppDir;
462 }
463
464 public String getResDir() {
465 return mResDir;
466 }
467
468 public String getDataDir() {
469 return mDataDir;
470 }
471
472 public File getDataDirFile() {
473 return mDataDirFile;
474 }
475
476 public AssetManager getAssets(ActivityThread mainThread) {
477 return getResources(mainThread).getAssets();
478 }
479
480 public Resources getResources(ActivityThread mainThread) {
481 if (mResources == null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700482 mResources = mainThread.getTopLevelResources(mResDir, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 }
484 return mResources;
485 }
486
Christopher Tate181fafa2009-05-14 11:12:14 -0700487 public Application makeApplication(boolean forceDefaultAppClass) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 if (mApplication != null) {
489 return mApplication;
490 }
Bob Leee5408332009-09-04 18:31:17 -0700491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 Application app = null;
Bob Leee5408332009-09-04 18:31:17 -0700493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 String appClass = mApplicationInfo.className;
Christopher Tate181fafa2009-05-14 11:12:14 -0700495 if (forceDefaultAppClass || (appClass == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 appClass = "android.app.Application";
497 }
498
499 try {
500 java.lang.ClassLoader cl = getClassLoader();
501 ApplicationContext appContext = new ApplicationContext();
502 appContext.init(this, null, mActivityThread);
503 app = mActivityThread.mInstrumentation.newApplication(
504 cl, appClass, appContext);
505 appContext.setOuterContext(app);
506 } catch (Exception e) {
507 if (!mActivityThread.mInstrumentation.onException(app, e)) {
508 throw new RuntimeException(
509 "Unable to instantiate application " + appClass
510 + ": " + e.toString(), e);
511 }
512 }
513 mActivityThread.mAllApplications.add(app);
514 return mApplication = app;
515 }
Bob Leee5408332009-09-04 18:31:17 -0700516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 public void removeContextRegistrations(Context context,
518 String who, String what) {
519 HashMap<BroadcastReceiver, ReceiverDispatcher> rmap =
520 mReceivers.remove(context);
521 if (rmap != null) {
522 Iterator<ReceiverDispatcher> it = rmap.values().iterator();
523 while (it.hasNext()) {
524 ReceiverDispatcher rd = it.next();
525 IntentReceiverLeaked leak = new IntentReceiverLeaked(
526 what + " " + who + " has leaked IntentReceiver "
527 + rd.getIntentReceiver() + " that was " +
528 "originally registered here. Are you missing a " +
529 "call to unregisterReceiver()?");
530 leak.setStackTrace(rd.getLocation().getStackTrace());
531 Log.e(TAG, leak.getMessage(), leak);
532 try {
533 ActivityManagerNative.getDefault().unregisterReceiver(
534 rd.getIIntentReceiver());
535 } catch (RemoteException e) {
536 // system crashed, nothing we can do
537 }
538 }
539 }
540 mUnregisteredReceivers.remove(context);
541 //Log.i(TAG, "Receiver registrations: " + mReceivers);
542 HashMap<ServiceConnection, ServiceDispatcher> smap =
543 mServices.remove(context);
544 if (smap != null) {
545 Iterator<ServiceDispatcher> it = smap.values().iterator();
546 while (it.hasNext()) {
547 ServiceDispatcher sd = it.next();
548 ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
549 what + " " + who + " has leaked ServiceConnection "
550 + sd.getServiceConnection() + " that was originally bound here");
551 leak.setStackTrace(sd.getLocation().getStackTrace());
552 Log.e(TAG, leak.getMessage(), leak);
553 try {
554 ActivityManagerNative.getDefault().unbindService(
555 sd.getIServiceConnection());
556 } catch (RemoteException e) {
557 // system crashed, nothing we can do
558 }
559 sd.doForget();
560 }
561 }
562 mUnboundServices.remove(context);
563 //Log.i(TAG, "Service registrations: " + mServices);
564 }
565
566 public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,
567 Context context, Handler handler,
568 Instrumentation instrumentation, boolean registered) {
569 synchronized (mReceivers) {
570 ReceiverDispatcher rd = null;
571 HashMap<BroadcastReceiver, ReceiverDispatcher> map = null;
572 if (registered) {
573 map = mReceivers.get(context);
574 if (map != null) {
575 rd = map.get(r);
576 }
577 }
578 if (rd == null) {
579 rd = new ReceiverDispatcher(r, context, handler,
580 instrumentation, registered);
581 if (registered) {
582 if (map == null) {
583 map = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
584 mReceivers.put(context, map);
585 }
586 map.put(r, rd);
587 }
588 } else {
589 rd.validate(context, handler);
590 }
591 return rd.getIIntentReceiver();
592 }
593 }
594
595 public IIntentReceiver forgetReceiverDispatcher(Context context,
596 BroadcastReceiver r) {
597 synchronized (mReceivers) {
598 HashMap<BroadcastReceiver, ReceiverDispatcher> map = mReceivers.get(context);
599 ReceiverDispatcher rd = null;
600 if (map != null) {
601 rd = map.get(r);
602 if (rd != null) {
603 map.remove(r);
604 if (map.size() == 0) {
605 mReceivers.remove(context);
606 }
607 if (r.getDebugUnregister()) {
608 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
609 = mUnregisteredReceivers.get(context);
610 if (holder == null) {
611 holder = new HashMap<BroadcastReceiver, ReceiverDispatcher>();
612 mUnregisteredReceivers.put(context, holder);
613 }
614 RuntimeException ex = new IllegalArgumentException(
615 "Originally unregistered here:");
616 ex.fillInStackTrace();
617 rd.setUnregisterLocation(ex);
618 holder.put(r, rd);
619 }
620 return rd.getIIntentReceiver();
621 }
622 }
623 HashMap<BroadcastReceiver, ReceiverDispatcher> holder
624 = mUnregisteredReceivers.get(context);
625 if (holder != null) {
626 rd = holder.get(r);
627 if (rd != null) {
628 RuntimeException ex = rd.getUnregisterLocation();
629 throw new IllegalArgumentException(
630 "Unregistering Receiver " + r
631 + " that was already unregistered", ex);
632 }
633 }
634 if (context == null) {
635 throw new IllegalStateException("Unbinding Receiver " + r
636 + " from Context that is no longer in use: " + context);
637 } else {
638 throw new IllegalArgumentException("Receiver not registered: " + r);
639 }
640
641 }
642 }
643
644 static final class ReceiverDispatcher {
645
646 final static class InnerReceiver extends IIntentReceiver.Stub {
647 final WeakReference<ReceiverDispatcher> mDispatcher;
648 final ReceiverDispatcher mStrongRef;
Bob Leee5408332009-09-04 18:31:17 -0700649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 InnerReceiver(ReceiverDispatcher rd, boolean strong) {
651 mDispatcher = new WeakReference<ReceiverDispatcher>(rd);
652 mStrongRef = strong ? rd : null;
653 }
654 public void performReceive(Intent intent, int resultCode,
655 String data, Bundle extras, boolean ordered) {
656 ReceiverDispatcher rd = mDispatcher.get();
657 if (DEBUG_BROADCAST) {
658 int seq = intent.getIntExtra("seq", -1);
659 Log.i(TAG, "Receiving broadcast " + intent.getAction() + " seq=" + seq
660 + " to " + rd);
661 }
662 if (rd != null) {
663 rd.performReceive(intent, resultCode, data, extras, ordered);
664 }
665 }
666 }
Bob Leee5408332009-09-04 18:31:17 -0700667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 final IIntentReceiver.Stub mIIntentReceiver;
669 final BroadcastReceiver mReceiver;
670 final Context mContext;
671 final Handler mActivityThread;
672 final Instrumentation mInstrumentation;
673 final boolean mRegistered;
674 final IntentReceiverLeaked mLocation;
675 RuntimeException mUnregisterLocation;
676
677 final class Args implements Runnable {
678 private Intent mCurIntent;
679 private int mCurCode;
680 private String mCurData;
681 private Bundle mCurMap;
682 private boolean mCurOrdered;
683
684 public void run() {
685 BroadcastReceiver receiver = mReceiver;
686 if (DEBUG_BROADCAST) {
687 int seq = mCurIntent.getIntExtra("seq", -1);
688 Log.i(TAG, "Dispathing broadcast " + mCurIntent.getAction() + " seq=" + seq
689 + " to " + mReceiver);
690 }
691 if (receiver == null) {
692 return;
693 }
694
695 IActivityManager mgr = ActivityManagerNative.getDefault();
696 Intent intent = mCurIntent;
697 mCurIntent = null;
698 try {
699 ClassLoader cl = mReceiver.getClass().getClassLoader();
700 intent.setExtrasClassLoader(cl);
701 if (mCurMap != null) {
702 mCurMap.setClassLoader(cl);
703 }
704 receiver.setOrderedHint(true);
705 receiver.setResult(mCurCode, mCurData, mCurMap);
706 receiver.clearAbortBroadcast();
707 receiver.setOrderedHint(mCurOrdered);
708 receiver.onReceive(mContext, intent);
709 } catch (Exception e) {
710 if (mRegistered && mCurOrdered) {
711 try {
712 mgr.finishReceiver(mIIntentReceiver,
713 mCurCode, mCurData, mCurMap, false);
714 } catch (RemoteException ex) {
715 }
716 }
717 if (mInstrumentation == null ||
718 !mInstrumentation.onException(mReceiver, e)) {
719 throw new RuntimeException(
720 "Error receiving broadcast " + intent
721 + " in " + mReceiver, e);
722 }
723 }
724 if (mRegistered && mCurOrdered) {
725 try {
726 mgr.finishReceiver(mIIntentReceiver,
727 receiver.getResultCode(),
728 receiver.getResultData(),
729 receiver.getResultExtras(false),
730 receiver.getAbortBroadcast());
731 } catch (RemoteException ex) {
732 }
733 }
734 }
735 }
736
737 ReceiverDispatcher(BroadcastReceiver receiver, Context context,
738 Handler activityThread, Instrumentation instrumentation,
739 boolean registered) {
740 if (activityThread == null) {
741 throw new NullPointerException("Handler must not be null");
742 }
743
744 mIIntentReceiver = new InnerReceiver(this, !registered);
745 mReceiver = receiver;
746 mContext = context;
747 mActivityThread = activityThread;
748 mInstrumentation = instrumentation;
749 mRegistered = registered;
750 mLocation = new IntentReceiverLeaked(null);
751 mLocation.fillInStackTrace();
752 }
753
754 void validate(Context context, Handler activityThread) {
755 if (mContext != context) {
756 throw new IllegalStateException(
757 "Receiver " + mReceiver +
758 " registered with differing Context (was " +
759 mContext + " now " + context + ")");
760 }
761 if (mActivityThread != activityThread) {
762 throw new IllegalStateException(
763 "Receiver " + mReceiver +
764 " registered with differing handler (was " +
765 mActivityThread + " now " + activityThread + ")");
766 }
767 }
768
769 IntentReceiverLeaked getLocation() {
770 return mLocation;
771 }
772
773 BroadcastReceiver getIntentReceiver() {
774 return mReceiver;
775 }
Bob Leee5408332009-09-04 18:31:17 -0700776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 IIntentReceiver getIIntentReceiver() {
778 return mIIntentReceiver;
779 }
780
781 void setUnregisterLocation(RuntimeException ex) {
782 mUnregisterLocation = ex;
783 }
784
785 RuntimeException getUnregisterLocation() {
786 return mUnregisterLocation;
787 }
788
789 public void performReceive(Intent intent, int resultCode,
790 String data, Bundle extras, boolean ordered) {
791 if (DEBUG_BROADCAST) {
792 int seq = intent.getIntExtra("seq", -1);
793 Log.i(TAG, "Enqueueing broadcast " + intent.getAction() + " seq=" + seq
794 + " to " + mReceiver);
795 }
796 Args args = new Args();
797 args.mCurIntent = intent;
798 args.mCurCode = resultCode;
799 args.mCurData = data;
800 args.mCurMap = extras;
801 args.mCurOrdered = ordered;
802 if (!mActivityThread.post(args)) {
803 if (mRegistered) {
804 IActivityManager mgr = ActivityManagerNative.getDefault();
805 try {
806 mgr.finishReceiver(mIIntentReceiver, args.mCurCode,
807 args.mCurData, args.mCurMap, false);
808 } catch (RemoteException ex) {
809 }
810 }
811 }
812 }
813
814 }
815
816 public final IServiceConnection getServiceDispatcher(ServiceConnection c,
817 Context context, Handler handler, int flags) {
818 synchronized (mServices) {
819 ServiceDispatcher sd = null;
820 HashMap<ServiceConnection, ServiceDispatcher> map = mServices.get(context);
821 if (map != null) {
822 sd = map.get(c);
823 }
824 if (sd == null) {
825 sd = new ServiceDispatcher(c, context, handler, flags);
826 if (map == null) {
827 map = new HashMap<ServiceConnection, ServiceDispatcher>();
828 mServices.put(context, map);
829 }
830 map.put(c, sd);
831 } else {
832 sd.validate(context, handler);
833 }
834 return sd.getIServiceConnection();
835 }
836 }
837
838 public final IServiceConnection forgetServiceDispatcher(Context context,
839 ServiceConnection c) {
840 synchronized (mServices) {
841 HashMap<ServiceConnection, ServiceDispatcher> map
842 = mServices.get(context);
843 ServiceDispatcher sd = null;
844 if (map != null) {
845 sd = map.get(c);
846 if (sd != null) {
847 map.remove(c);
848 sd.doForget();
849 if (map.size() == 0) {
850 mServices.remove(context);
851 }
852 if ((sd.getFlags()&Context.BIND_DEBUG_UNBIND) != 0) {
853 HashMap<ServiceConnection, ServiceDispatcher> holder
854 = mUnboundServices.get(context);
855 if (holder == null) {
856 holder = new HashMap<ServiceConnection, ServiceDispatcher>();
857 mUnboundServices.put(context, holder);
858 }
859 RuntimeException ex = new IllegalArgumentException(
860 "Originally unbound here:");
861 ex.fillInStackTrace();
862 sd.setUnbindLocation(ex);
863 holder.put(c, sd);
864 }
865 return sd.getIServiceConnection();
866 }
867 }
868 HashMap<ServiceConnection, ServiceDispatcher> holder
869 = mUnboundServices.get(context);
870 if (holder != null) {
871 sd = holder.get(c);
872 if (sd != null) {
873 RuntimeException ex = sd.getUnbindLocation();
874 throw new IllegalArgumentException(
875 "Unbinding Service " + c
876 + " that was already unbound", ex);
877 }
878 }
879 if (context == null) {
880 throw new IllegalStateException("Unbinding Service " + c
881 + " from Context that is no longer in use: " + context);
882 } else {
883 throw new IllegalArgumentException("Service not registered: " + c);
884 }
885 }
886 }
887
888 static final class ServiceDispatcher {
889 private final InnerConnection mIServiceConnection;
890 private final ServiceConnection mConnection;
891 private final Context mContext;
892 private final Handler mActivityThread;
893 private final ServiceConnectionLeaked mLocation;
894 private final int mFlags;
895
896 private RuntimeException mUnbindLocation;
897
898 private boolean mDied;
899
900 private static class ConnectionInfo {
901 IBinder binder;
902 IBinder.DeathRecipient deathMonitor;
903 }
904
905 private static class InnerConnection extends IServiceConnection.Stub {
906 final WeakReference<ServiceDispatcher> mDispatcher;
Bob Leee5408332009-09-04 18:31:17 -0700907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 InnerConnection(ServiceDispatcher sd) {
909 mDispatcher = new WeakReference<ServiceDispatcher>(sd);
910 }
911
912 public void connected(ComponentName name, IBinder service) throws RemoteException {
913 ServiceDispatcher sd = mDispatcher.get();
914 if (sd != null) {
915 sd.connected(name, service);
916 }
917 }
918 }
Bob Leee5408332009-09-04 18:31:17 -0700919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 private final HashMap<ComponentName, ConnectionInfo> mActiveConnections
921 = new HashMap<ComponentName, ConnectionInfo>();
922
923 ServiceDispatcher(ServiceConnection conn,
924 Context context, Handler activityThread, int flags) {
925 mIServiceConnection = new InnerConnection(this);
926 mConnection = conn;
927 mContext = context;
928 mActivityThread = activityThread;
929 mLocation = new ServiceConnectionLeaked(null);
930 mLocation.fillInStackTrace();
931 mFlags = flags;
932 }
933
934 void validate(Context context, Handler activityThread) {
935 if (mContext != context) {
936 throw new RuntimeException(
937 "ServiceConnection " + mConnection +
938 " registered with differing Context (was " +
939 mContext + " now " + context + ")");
940 }
941 if (mActivityThread != activityThread) {
942 throw new RuntimeException(
943 "ServiceConnection " + mConnection +
944 " registered with differing handler (was " +
945 mActivityThread + " now " + activityThread + ")");
946 }
947 }
948
949 void doForget() {
950 synchronized(this) {
951 Iterator<ConnectionInfo> it = mActiveConnections.values().iterator();
952 while (it.hasNext()) {
953 ConnectionInfo ci = it.next();
954 ci.binder.unlinkToDeath(ci.deathMonitor, 0);
955 }
956 mActiveConnections.clear();
957 }
958 }
959
960 ServiceConnectionLeaked getLocation() {
961 return mLocation;
962 }
963
964 ServiceConnection getServiceConnection() {
965 return mConnection;
966 }
967
968 IServiceConnection getIServiceConnection() {
969 return mIServiceConnection;
970 }
Bob Leee5408332009-09-04 18:31:17 -0700971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 int getFlags() {
973 return mFlags;
974 }
975
976 void setUnbindLocation(RuntimeException ex) {
977 mUnbindLocation = ex;
978 }
979
980 RuntimeException getUnbindLocation() {
981 return mUnbindLocation;
982 }
983
984 public void connected(ComponentName name, IBinder service) {
985 if (mActivityThread != null) {
986 mActivityThread.post(new RunConnection(name, service, 0));
987 } else {
988 doConnected(name, service);
989 }
990 }
991
992 public void death(ComponentName name, IBinder service) {
993 ConnectionInfo old;
994
995 synchronized (this) {
996 mDied = true;
997 old = mActiveConnections.remove(name);
998 if (old == null || old.binder != service) {
999 // Death for someone different than who we last
1000 // reported... just ignore it.
1001 return;
1002 }
1003 old.binder.unlinkToDeath(old.deathMonitor, 0);
1004 }
1005
1006 if (mActivityThread != null) {
1007 mActivityThread.post(new RunConnection(name, service, 1));
1008 } else {
1009 doDeath(name, service);
1010 }
1011 }
1012
1013 public void doConnected(ComponentName name, IBinder service) {
1014 ConnectionInfo old;
1015 ConnectionInfo info;
1016
1017 synchronized (this) {
1018 old = mActiveConnections.get(name);
1019 if (old != null && old.binder == service) {
1020 // Huh, already have this one. Oh well!
1021 return;
1022 }
1023
1024 if (service != null) {
1025 // A new service is being connected... set it all up.
1026 mDied = false;
1027 info = new ConnectionInfo();
1028 info.binder = service;
1029 info.deathMonitor = new DeathMonitor(name, service);
1030 try {
1031 service.linkToDeath(info.deathMonitor, 0);
1032 mActiveConnections.put(name, info);
1033 } catch (RemoteException e) {
1034 // This service was dead before we got it... just
1035 // don't do anything with it.
1036 mActiveConnections.remove(name);
1037 return;
1038 }
1039
1040 } else {
1041 // The named service is being disconnected... clean up.
1042 mActiveConnections.remove(name);
1043 }
1044
1045 if (old != null) {
1046 old.binder.unlinkToDeath(old.deathMonitor, 0);
1047 }
1048 }
1049
1050 // If there was an old service, it is not disconnected.
1051 if (old != null) {
1052 mConnection.onServiceDisconnected(name);
1053 }
1054 // If there is a new service, it is now connected.
1055 if (service != null) {
1056 mConnection.onServiceConnected(name, service);
1057 }
1058 }
1059
1060 public void doDeath(ComponentName name, IBinder service) {
1061 mConnection.onServiceDisconnected(name);
1062 }
1063
1064 private final class RunConnection implements Runnable {
1065 RunConnection(ComponentName name, IBinder service, int command) {
1066 mName = name;
1067 mService = service;
1068 mCommand = command;
1069 }
1070
1071 public void run() {
1072 if (mCommand == 0) {
1073 doConnected(mName, mService);
1074 } else if (mCommand == 1) {
1075 doDeath(mName, mService);
1076 }
1077 }
1078
1079 final ComponentName mName;
1080 final IBinder mService;
1081 final int mCommand;
1082 }
1083
1084 private final class DeathMonitor implements IBinder.DeathRecipient
1085 {
1086 DeathMonitor(ComponentName name, IBinder service) {
1087 mName = name;
1088 mService = service;
1089 }
1090
1091 public void binderDied() {
1092 death(mName, mService);
1093 }
1094
1095 final ComponentName mName;
1096 final IBinder mService;
1097 }
1098 }
1099 }
1100
1101 private static ApplicationContext mSystemContext = null;
1102
1103 private static final class ActivityRecord {
1104 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001105 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 Intent intent;
1107 Bundle state;
1108 Activity activity;
1109 Window window;
1110 Activity parent;
1111 String embeddedID;
1112 Object lastNonConfigurationInstance;
1113 HashMap<String,Object> lastNonConfigurationChildInstances;
1114 boolean paused;
1115 boolean stopped;
1116 boolean hideForNow;
1117 Configuration newConfig;
1118 ActivityRecord nextIdle;
1119
1120 ActivityInfo activityInfo;
1121 PackageInfo packageInfo;
1122
1123 List<ResultInfo> pendingResults;
1124 List<Intent> pendingIntents;
1125
1126 boolean startsNotResumed;
1127 boolean isForward;
1128
1129 ActivityRecord() {
1130 parent = null;
1131 embeddedID = null;
1132 paused = false;
1133 stopped = false;
1134 hideForNow = false;
1135 nextIdle = null;
1136 }
1137
1138 public String toString() {
1139 ComponentName componentName = intent.getComponent();
1140 return "ActivityRecord{"
1141 + Integer.toHexString(System.identityHashCode(this))
1142 + " token=" + token + " " + (componentName == null
1143 ? "no component name" : componentName.toShortString())
1144 + "}";
1145 }
1146 }
1147
1148 private final class ProviderRecord implements IBinder.DeathRecipient {
1149 final String mName;
1150 final IContentProvider mProvider;
1151 final ContentProvider mLocalProvider;
1152
1153 ProviderRecord(String name, IContentProvider provider,
1154 ContentProvider localProvider) {
1155 mName = name;
1156 mProvider = provider;
1157 mLocalProvider = localProvider;
1158 }
1159
1160 public void binderDied() {
1161 removeDeadProvider(mName, mProvider);
1162 }
1163 }
1164
1165 private static final class NewIntentData {
1166 List<Intent> intents;
1167 IBinder token;
1168 public String toString() {
1169 return "NewIntentData{intents=" + intents + " token=" + token + "}";
1170 }
1171 }
1172
1173 private static final class ReceiverData {
1174 Intent intent;
1175 ActivityInfo info;
1176 int resultCode;
1177 String resultData;
1178 Bundle resultExtras;
1179 boolean sync;
1180 boolean resultAbort;
1181 public String toString() {
1182 return "ReceiverData{intent=" + intent + " packageName=" +
1183 info.packageName + " resultCode=" + resultCode
1184 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
1185 }
1186 }
1187
Christopher Tate181fafa2009-05-14 11:12:14 -07001188 private static final class CreateBackupAgentData {
1189 ApplicationInfo appInfo;
1190 int backupMode;
1191 public String toString() {
1192 return "CreateBackupAgentData{appInfo=" + appInfo
1193 + " backupAgent=" + appInfo.backupAgentName
1194 + " mode=" + backupMode + "}";
1195 }
1196 }
Bob Leee5408332009-09-04 18:31:17 -07001197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 private static final class CreateServiceData {
1199 IBinder token;
1200 ServiceInfo info;
1201 Intent intent;
1202 public String toString() {
1203 return "CreateServiceData{token=" + token + " className="
1204 + info.name + " packageName=" + info.packageName
1205 + " intent=" + intent + "}";
1206 }
1207 }
1208
1209 private static final class BindServiceData {
1210 IBinder token;
1211 Intent intent;
1212 boolean rebind;
1213 public String toString() {
1214 return "BindServiceData{token=" + token + " intent=" + intent + "}";
1215 }
1216 }
1217
1218 private static final class ServiceArgsData {
1219 IBinder token;
1220 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001221 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 Intent args;
1223 public String toString() {
1224 return "ServiceArgsData{token=" + token + " startId=" + startId
1225 + " args=" + args + "}";
1226 }
1227 }
1228
1229 private static final class AppBindData {
1230 PackageInfo info;
1231 String processName;
1232 ApplicationInfo appInfo;
1233 List<ProviderInfo> providers;
1234 ComponentName instrumentationName;
1235 String profileFile;
1236 Bundle instrumentationArgs;
1237 IInstrumentationWatcher instrumentationWatcher;
1238 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001239 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 Configuration config;
1241 boolean handlingProfiling;
1242 public String toString() {
1243 return "AppBindData{appInfo=" + appInfo + "}";
1244 }
1245 }
1246
1247 private static final class DumpServiceInfo {
1248 FileDescriptor fd;
1249 IBinder service;
1250 String[] args;
1251 boolean dumped;
1252 }
1253
1254 private static final class ResultData {
1255 IBinder token;
1256 List<ResultInfo> results;
1257 public String toString() {
1258 return "ResultData{token=" + token + " results" + results + "}";
1259 }
1260 }
1261
1262 private static final class ContextCleanupInfo {
1263 ApplicationContext context;
1264 String what;
1265 String who;
1266 }
1267
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001268 private static final class ProfilerControlData {
1269 String path;
1270 ParcelFileDescriptor fd;
1271 }
1272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 private final class ApplicationThread extends ApplicationThreadNative {
1274 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
1275 private static final String ONE_COUNT_COLUMN = "%17s %8d";
1276 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Bob Leee5408332009-09-04 18:31:17 -07001277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 // Formatting for checkin service - update version if row format changes
1279 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -07001280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 public final void schedulePauseActivity(IBinder token, boolean finished,
1282 boolean userLeaving, int configChanges) {
1283 queueOrSendMessage(
1284 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
1285 token,
1286 (userLeaving ? 1 : 0),
1287 configChanges);
1288 }
1289
1290 public final void scheduleStopActivity(IBinder token, boolean showWindow,
1291 int configChanges) {
1292 queueOrSendMessage(
1293 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
1294 token, 0, configChanges);
1295 }
1296
1297 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
1298 queueOrSendMessage(
1299 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
1300 token);
1301 }
1302
1303 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
1304 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
1305 }
1306
1307 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
1308 ResultData res = new ResultData();
1309 res.token = token;
1310 res.results = results;
1311 queueOrSendMessage(H.SEND_RESULT, res);
1312 }
1313
1314 // we use token to identify this activity without having to send the
1315 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001316 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
1318 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
1319 ActivityRecord r = new ActivityRecord();
1320
1321 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001322 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 r.intent = intent;
1324 r.activityInfo = info;
1325 r.state = state;
1326
1327 r.pendingResults = pendingResults;
1328 r.pendingIntents = pendingNewIntents;
1329
1330 r.startsNotResumed = notResumed;
1331 r.isForward = isForward;
1332
1333 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
1334 }
1335
1336 public final void scheduleRelaunchActivity(IBinder token,
1337 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
1338 int configChanges, boolean notResumed) {
1339 ActivityRecord r = new ActivityRecord();
1340
1341 r.token = token;
1342 r.pendingResults = pendingResults;
1343 r.pendingIntents = pendingNewIntents;
1344 r.startsNotResumed = notResumed;
1345
1346 synchronized (mRelaunchingActivities) {
1347 mRelaunchingActivities.add(r);
1348 }
Bob Leee5408332009-09-04 18:31:17 -07001349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
1351 }
1352
1353 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
1354 NewIntentData data = new NewIntentData();
1355 data.intents = intents;
1356 data.token = token;
1357
1358 queueOrSendMessage(H.NEW_INTENT, data);
1359 }
1360
1361 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
1362 int configChanges) {
1363 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
1364 configChanges);
1365 }
1366
1367 public final void scheduleReceiver(Intent intent, ActivityInfo info,
1368 int resultCode, String data, Bundle extras, boolean sync) {
1369 ReceiverData r = new ReceiverData();
1370
1371 r.intent = intent;
1372 r.info = info;
1373 r.resultCode = resultCode;
1374 r.resultData = data;
1375 r.resultExtras = extras;
1376 r.sync = sync;
1377
1378 queueOrSendMessage(H.RECEIVER, r);
1379 }
1380
Christopher Tate181fafa2009-05-14 11:12:14 -07001381 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
1382 CreateBackupAgentData d = new CreateBackupAgentData();
1383 d.appInfo = app;
1384 d.backupMode = backupMode;
1385
1386 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
1387 }
1388
1389 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
1390 CreateBackupAgentData d = new CreateBackupAgentData();
1391 d.appInfo = app;
1392
1393 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
1394 }
1395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 public final void scheduleCreateService(IBinder token,
1397 ServiceInfo info) {
1398 CreateServiceData s = new CreateServiceData();
1399 s.token = token;
1400 s.info = info;
1401
1402 queueOrSendMessage(H.CREATE_SERVICE, s);
1403 }
1404
1405 public final void scheduleBindService(IBinder token, Intent intent,
1406 boolean rebind) {
1407 BindServiceData s = new BindServiceData();
1408 s.token = token;
1409 s.intent = intent;
1410 s.rebind = rebind;
1411
1412 queueOrSendMessage(H.BIND_SERVICE, s);
1413 }
1414
1415 public final void scheduleUnbindService(IBinder token, Intent intent) {
1416 BindServiceData s = new BindServiceData();
1417 s.token = token;
1418 s.intent = intent;
1419
1420 queueOrSendMessage(H.UNBIND_SERVICE, s);
1421 }
1422
1423 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001424 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 ServiceArgsData s = new ServiceArgsData();
1426 s.token = token;
1427 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001428 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 s.args = args;
1430
1431 queueOrSendMessage(H.SERVICE_ARGS, s);
1432 }
1433
1434 public final void scheduleStopService(IBinder token) {
1435 queueOrSendMessage(H.STOP_SERVICE, token);
1436 }
1437
1438 public final void bindApplication(String processName,
1439 ApplicationInfo appInfo, List<ProviderInfo> providers,
1440 ComponentName instrumentationName, String profileFile,
1441 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -07001442 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 Map<String, IBinder> services) {
1444 Process.setArgV0(processName);
1445
1446 if (services != null) {
1447 // Setup the service cache in the ServiceManager
1448 ServiceManager.initServiceCache(services);
1449 }
1450
1451 AppBindData data = new AppBindData();
1452 data.processName = processName;
1453 data.appInfo = appInfo;
1454 data.providers = providers;
1455 data.instrumentationName = instrumentationName;
1456 data.profileFile = profileFile;
1457 data.instrumentationArgs = instrumentationArgs;
1458 data.instrumentationWatcher = instrumentationWatcher;
1459 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -07001460 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 data.config = config;
1462 queueOrSendMessage(H.BIND_APPLICATION, data);
1463 }
1464
1465 public final void scheduleExit() {
1466 queueOrSendMessage(H.EXIT_APPLICATION, null);
1467 }
1468
Christopher Tate5e1ab332009-09-01 20:32:49 -07001469 public final void scheduleSuicide() {
1470 queueOrSendMessage(H.SUICIDE, null);
1471 }
1472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 public void requestThumbnail(IBinder token) {
1474 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
1475 }
1476
1477 public void scheduleConfigurationChanged(Configuration config) {
1478 synchronized (mRelaunchingActivities) {
1479 mPendingConfiguration = config;
1480 }
1481 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
1482 }
1483
1484 public void updateTimeZone() {
1485 TimeZone.setDefault(null);
1486 }
1487
1488 public void processInBackground() {
1489 mH.removeMessages(H.GC_WHEN_IDLE);
1490 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1491 }
1492
1493 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
1494 DumpServiceInfo data = new DumpServiceInfo();
1495 data.fd = fd;
1496 data.service = servicetoken;
1497 data.args = args;
1498 data.dumped = false;
1499 queueOrSendMessage(H.DUMP_SERVICE, data);
1500 synchronized (data) {
1501 while (!data.dumped) {
1502 try {
1503 data.wait();
1504 } catch (InterruptedException e) {
1505 // no need to do anything here, we will keep waiting until
1506 // dumped is set
1507 }
1508 }
1509 }
1510 }
1511
1512 // This function exists to make sure all receiver dispatching is
1513 // correctly ordered, since these are one-way calls and the binder driver
1514 // applies transaction ordering per object for such calls.
1515 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
1516 int resultCode, String dataStr, Bundle extras, boolean ordered)
1517 throws RemoteException {
1518 receiver.performReceive(intent, resultCode, dataStr, extras, ordered);
1519 }
Bob Leee5408332009-09-04 18:31:17 -07001520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 public void scheduleLowMemory() {
1522 queueOrSendMessage(H.LOW_MEMORY, null);
1523 }
1524
1525 public void scheduleActivityConfigurationChanged(IBinder token) {
1526 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
1527 }
1528
1529 public void requestPss() {
1530 try {
1531 ActivityManagerNative.getDefault().reportPss(this,
1532 (int)Process.getPss(Process.myPid()));
1533 } catch (RemoteException e) {
1534 }
1535 }
Bob Leee5408332009-09-04 18:31:17 -07001536
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001537 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
1538 ProfilerControlData pcd = new ProfilerControlData();
1539 pcd.path = path;
1540 pcd.fd = fd;
1541 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001542 }
1543
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001544 public void setSchedulingGroup(int group) {
1545 // Note: do this immediately, since going into the foreground
1546 // should happen regardless of what pending work we have to do
1547 // and the activity manager will wait for us to report back that
1548 // we are done before sending us to the background.
1549 try {
1550 Process.setProcessGroup(Process.myPid(), group);
1551 } catch (Exception e) {
1552 Log.w(TAG, "Failed setting process group to " + group, e);
1553 }
1554 }
Bob Leee5408332009-09-04 18:31:17 -07001555
Dianne Hackborn3025ef32009-08-31 21:31:47 -07001556 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
1557 Debug.getMemoryInfo(outInfo);
1558 }
Bob Leee5408332009-09-04 18:31:17 -07001559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 @Override
1561 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1562 long nativeMax = Debug.getNativeHeapSize() / 1024;
1563 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1564 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1565
1566 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
1567 Debug.getMemoryInfo(memInfo);
1568
1569 final int nativeShared = memInfo.nativeSharedDirty;
1570 final int dalvikShared = memInfo.dalvikSharedDirty;
1571 final int otherShared = memInfo.otherSharedDirty;
1572
1573 final int nativePrivate = memInfo.nativePrivateDirty;
1574 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
1575 final int otherPrivate = memInfo.otherPrivateDirty;
1576
1577 Runtime runtime = Runtime.getRuntime();
1578
1579 long dalvikMax = runtime.totalMemory() / 1024;
1580 long dalvikFree = runtime.freeMemory() / 1024;
1581 long dalvikAllocated = dalvikMax - dalvikFree;
1582 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1583 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
1584 long appContextInstanceCount = ApplicationContext.getInstanceCount();
1585 long activityInstanceCount = Activity.getInstanceCount();
1586 int globalAssetCount = AssetManager.getGlobalAssetCount();
1587 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1588 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1589 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1590 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1591 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
1592 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
1593 SQLiteDebug.PagerStats stats = new SQLiteDebug.PagerStats();
1594 SQLiteDebug.getPagerStats(stats);
Bob Leee5408332009-09-04 18:31:17 -07001595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 // Check to see if we were called by checkin server. If so, print terse format.
1597 boolean doCheckinFormat = false;
1598 if (args != null) {
1599 for (String arg : args) {
1600 if ("-c".equals(arg)) doCheckinFormat = true;
1601 }
1602 }
Bob Leee5408332009-09-04 18:31:17 -07001603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 // For checkin, we print one long comma-separated list of values
1605 if (doCheckinFormat) {
1606 // NOTE: if you change anything significant below, also consider changing
1607 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -07001608 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -07001610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 // Header
1612 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
1613 pw.print(Process.myPid()); pw.print(',');
1614 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 // Heap info - max
1617 pw.print(nativeMax); pw.print(',');
1618 pw.print(dalvikMax); pw.print(',');
1619 pw.print("N/A,");
1620 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 // Heap info - allocated
1623 pw.print(nativeAllocated); pw.print(',');
1624 pw.print(dalvikAllocated); pw.print(',');
1625 pw.print("N/A,");
1626 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 // Heap info - free
1629 pw.print(nativeFree); pw.print(',');
1630 pw.print(dalvikFree); pw.print(',');
1631 pw.print("N/A,");
1632 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 // Heap info - proportional set size
1635 pw.print(memInfo.nativePss); pw.print(',');
1636 pw.print(memInfo.dalvikPss); pw.print(',');
1637 pw.print(memInfo.otherPss); pw.print(',');
1638 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -07001641 pw.print(nativeShared); pw.print(',');
1642 pw.print(dalvikShared); pw.print(',');
1643 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -07001647 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 pw.print(dalvikPrivate); pw.print(',');
1649 pw.print(otherPrivate); pw.print(',');
1650 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 // Object counts
1653 pw.print(viewInstanceCount); pw.print(',');
1654 pw.print(viewRootInstanceCount); pw.print(',');
1655 pw.print(appContextInstanceCount); pw.print(',');
1656 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 pw.print(globalAssetCount); pw.print(',');
1659 pw.print(globalAssetManagerCount); pw.print(',');
1660 pw.print(binderLocalObjectCount); pw.print(',');
1661 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 pw.print(binderDeathObjectCount); pw.print(',');
1664 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 // SQL
1667 pw.print(sqliteAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001668 pw.print(stats.databaseBytes / 1024); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 pw.print(stats.numPagers); pw.print(',');
1670 pw.print((stats.totalBytes - stats.referencedBytes) / 1024); pw.print(',');
1671 pw.print(stats.referencedBytes / 1024); pw.print('\n');
Bob Leee5408332009-09-04 18:31:17 -07001672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 return;
1674 }
Bob Leee5408332009-09-04 18:31:17 -07001675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 // otherwise, show human-readable format
1677 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
1678 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
1679 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
1680 nativeAllocated + dalvikAllocated);
1681 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
1682 nativeFree + dalvikFree);
1683
1684 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
1685 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
1686
1687 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
1688 nativeShared + dalvikShared + otherShared);
1689 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
1690 nativePrivate + dalvikPrivate + otherPrivate);
1691
1692 pw.println(" ");
1693 pw.println(" Objects");
1694 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
1695 viewRootInstanceCount);
1696
1697 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1698 "Activities:", activityInstanceCount);
1699
1700 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1701 "AssetManagers:", globalAssetManagerCount);
1702
1703 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1704 "Proxy Binders:", binderProxyObjectCount);
1705 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1706
1707 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 // SQLite mem info
1710 pw.println(" ");
1711 pw.println(" SQL");
1712 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "dbFiles:",
1713 stats.databaseBytes / 1024);
1714 printRow(pw, TWO_COUNT_COLUMNS, "numPagers:", stats.numPagers, "inactivePageKB:",
1715 (stats.totalBytes - stats.referencedBytes) / 1024);
1716 printRow(pw, ONE_COUNT_COLUMN, "activePageKB:", stats.referencedBytes / 1024);
Bob Leee5408332009-09-04 18:31:17 -07001717
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001718 // Asset details.
1719 String assetAlloc = AssetManager.getAssetAllocations();
1720 if (assetAlloc != null) {
1721 pw.println(" ");
1722 pw.println(" Asset Allocations");
1723 pw.print(assetAlloc);
1724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726
1727 private void printRow(PrintWriter pw, String format, Object...objs) {
1728 pw.println(String.format(format, objs));
1729 }
1730 }
1731
1732 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -07001733 private H() {
1734 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
1735 }
1736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 public static final int LAUNCH_ACTIVITY = 100;
1738 public static final int PAUSE_ACTIVITY = 101;
1739 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1740 public static final int STOP_ACTIVITY_SHOW = 103;
1741 public static final int STOP_ACTIVITY_HIDE = 104;
1742 public static final int SHOW_WINDOW = 105;
1743 public static final int HIDE_WINDOW = 106;
1744 public static final int RESUME_ACTIVITY = 107;
1745 public static final int SEND_RESULT = 108;
1746 public static final int DESTROY_ACTIVITY = 109;
1747 public static final int BIND_APPLICATION = 110;
1748 public static final int EXIT_APPLICATION = 111;
1749 public static final int NEW_INTENT = 112;
1750 public static final int RECEIVER = 113;
1751 public static final int CREATE_SERVICE = 114;
1752 public static final int SERVICE_ARGS = 115;
1753 public static final int STOP_SERVICE = 116;
1754 public static final int REQUEST_THUMBNAIL = 117;
1755 public static final int CONFIGURATION_CHANGED = 118;
1756 public static final int CLEAN_UP_CONTEXT = 119;
1757 public static final int GC_WHEN_IDLE = 120;
1758 public static final int BIND_SERVICE = 121;
1759 public static final int UNBIND_SERVICE = 122;
1760 public static final int DUMP_SERVICE = 123;
1761 public static final int LOW_MEMORY = 124;
1762 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1763 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001764 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001765 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001766 public static final int DESTROY_BACKUP_AGENT = 129;
1767 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001768 public static final int REMOVE_PROVIDER = 131;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 String codeToString(int code) {
1770 if (localLOGV) {
1771 switch (code) {
1772 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1773 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1774 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1775 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1776 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1777 case SHOW_WINDOW: return "SHOW_WINDOW";
1778 case HIDE_WINDOW: return "HIDE_WINDOW";
1779 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1780 case SEND_RESULT: return "SEND_RESULT";
1781 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1782 case BIND_APPLICATION: return "BIND_APPLICATION";
1783 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1784 case NEW_INTENT: return "NEW_INTENT";
1785 case RECEIVER: return "RECEIVER";
1786 case CREATE_SERVICE: return "CREATE_SERVICE";
1787 case SERVICE_ARGS: return "SERVICE_ARGS";
1788 case STOP_SERVICE: return "STOP_SERVICE";
1789 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1790 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1791 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1792 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1793 case BIND_SERVICE: return "BIND_SERVICE";
1794 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1795 case DUMP_SERVICE: return "DUMP_SERVICE";
1796 case LOW_MEMORY: return "LOW_MEMORY";
1797 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1798 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001799 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001800 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1801 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001802 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001803 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
1805 }
1806 return "(unknown)";
1807 }
1808 public void handleMessage(Message msg) {
1809 switch (msg.what) {
1810 case LAUNCH_ACTIVITY: {
1811 ActivityRecord r = (ActivityRecord)msg.obj;
1812
1813 r.packageInfo = getPackageInfoNoCheck(
1814 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001815 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 } break;
1817 case RELAUNCH_ACTIVITY: {
1818 ActivityRecord r = (ActivityRecord)msg.obj;
1819 handleRelaunchActivity(r, msg.arg1);
1820 } break;
1821 case PAUSE_ACTIVITY:
1822 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001823 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 break;
1825 case PAUSE_ACTIVITY_FINISHING:
1826 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1827 break;
1828 case STOP_ACTIVITY_SHOW:
1829 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1830 break;
1831 case STOP_ACTIVITY_HIDE:
1832 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1833 break;
1834 case SHOW_WINDOW:
1835 handleWindowVisibility((IBinder)msg.obj, true);
1836 break;
1837 case HIDE_WINDOW:
1838 handleWindowVisibility((IBinder)msg.obj, false);
1839 break;
1840 case RESUME_ACTIVITY:
1841 handleResumeActivity((IBinder)msg.obj, true,
1842 msg.arg1 != 0);
1843 break;
1844 case SEND_RESULT:
1845 handleSendResult((ResultData)msg.obj);
1846 break;
1847 case DESTROY_ACTIVITY:
1848 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1849 msg.arg2, false);
1850 break;
1851 case BIND_APPLICATION:
1852 AppBindData data = (AppBindData)msg.obj;
1853 handleBindApplication(data);
1854 break;
1855 case EXIT_APPLICATION:
1856 if (mInitialApplication != null) {
1857 mInitialApplication.onTerminate();
1858 }
1859 Looper.myLooper().quit();
1860 break;
1861 case NEW_INTENT:
1862 handleNewIntent((NewIntentData)msg.obj);
1863 break;
1864 case RECEIVER:
1865 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001866 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 break;
1868 case CREATE_SERVICE:
1869 handleCreateService((CreateServiceData)msg.obj);
1870 break;
1871 case BIND_SERVICE:
1872 handleBindService((BindServiceData)msg.obj);
1873 break;
1874 case UNBIND_SERVICE:
1875 handleUnbindService((BindServiceData)msg.obj);
1876 break;
1877 case SERVICE_ARGS:
1878 handleServiceArgs((ServiceArgsData)msg.obj);
1879 break;
1880 case STOP_SERVICE:
1881 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001882 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 break;
1884 case REQUEST_THUMBNAIL:
1885 handleRequestThumbnail((IBinder)msg.obj);
1886 break;
1887 case CONFIGURATION_CHANGED:
1888 handleConfigurationChanged((Configuration)msg.obj);
1889 break;
1890 case CLEAN_UP_CONTEXT:
1891 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1892 cci.context.performFinalCleanup(cci.who, cci.what);
1893 break;
1894 case GC_WHEN_IDLE:
1895 scheduleGcIdler();
1896 break;
1897 case DUMP_SERVICE:
1898 handleDumpService((DumpServiceInfo)msg.obj);
1899 break;
1900 case LOW_MEMORY:
1901 handleLowMemory();
1902 break;
1903 case ACTIVITY_CONFIGURATION_CHANGED:
1904 handleActivityConfigurationChanged((IBinder)msg.obj);
1905 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001906 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001907 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001908 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001909 case CREATE_BACKUP_AGENT:
1910 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1911 break;
1912 case DESTROY_BACKUP_AGENT:
1913 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1914 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001915 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001916 Process.killProcess(Process.myPid());
1917 break;
1918 case REMOVE_PROVIDER:
1919 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001920 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 }
1922 }
Bob Leee5408332009-09-04 18:31:17 -07001923
1924 void maybeSnapshot() {
1925 if (mBoundApplication != null) {
1926 SamplingProfilerIntegration.writeSnapshot(
1927 mBoundApplication.processName);
1928 }
1929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 }
1931
1932 private final class Idler implements MessageQueue.IdleHandler {
1933 public final boolean queueIdle() {
1934 ActivityRecord a = mNewActivities;
1935 if (a != null) {
1936 mNewActivities = null;
1937 IActivityManager am = ActivityManagerNative.getDefault();
1938 ActivityRecord prev;
1939 do {
1940 if (localLOGV) Log.v(
1941 TAG, "Reporting idle of " + a +
1942 " finished=" +
1943 (a.activity != null ? a.activity.mFinished : false));
1944 if (a.activity != null && !a.activity.mFinished) {
1945 try {
1946 am.activityIdle(a.token);
1947 } catch (RemoteException ex) {
1948 }
1949 }
1950 prev = a;
1951 a = a.nextIdle;
1952 prev.nextIdle = null;
1953 } while (a != null);
1954 }
1955 return false;
1956 }
1957 }
1958
1959 final class GcIdler implements MessageQueue.IdleHandler {
1960 public final boolean queueIdle() {
1961 doGcIfNeeded();
1962 return false;
1963 }
1964 }
1965
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001966 private final static class ResourcesKey {
1967 final private String mResDir;
1968 final private float mScale;
1969 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001970
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001971 ResourcesKey(String resDir, float scale) {
1972 mResDir = resDir;
1973 mScale = scale;
1974 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1975 }
Bob Leee5408332009-09-04 18:31:17 -07001976
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001977 @Override
1978 public int hashCode() {
1979 return mHash;
1980 }
1981
1982 @Override
1983 public boolean equals(Object obj) {
1984 if (!(obj instanceof ResourcesKey)) {
1985 return false;
1986 }
1987 ResourcesKey peer = (ResourcesKey) obj;
1988 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1989 }
1990 }
1991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 static IPackageManager sPackageManager;
1993
1994 final ApplicationThread mAppThread = new ApplicationThread();
1995 final Looper mLooper = Looper.myLooper();
1996 final H mH = new H();
1997 final HashMap<IBinder, ActivityRecord> mActivities
1998 = new HashMap<IBinder, ActivityRecord>();
1999 // List of new activities (via ActivityRecord.nextIdle) that should
2000 // be reported when next we idle.
2001 ActivityRecord mNewActivities = null;
2002 // Number of activities that are currently visible on-screen.
2003 int mNumVisibleActivities = 0;
2004 final HashMap<IBinder, Service> mServices
2005 = new HashMap<IBinder, Service>();
2006 AppBindData mBoundApplication;
2007 Configuration mConfiguration;
2008 Application mInitialApplication;
2009 final ArrayList<Application> mAllApplications
2010 = new ArrayList<Application>();
Christopher Tate181fafa2009-05-14 11:12:14 -07002011 // set of instantiated backup agents, keyed by package name
2012 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 static final ThreadLocal sThreadLocal = new ThreadLocal();
2014 Instrumentation mInstrumentation;
2015 String mInstrumentationAppDir = null;
2016 String mInstrumentationAppPackage = null;
2017 String mInstrumentedAppDir = null;
2018 boolean mSystemThread = false;
2019
2020 /**
2021 * Activities that are enqueued to be relaunched. This list is accessed
2022 * by multiple threads, so you must synchronize on it when accessing it.
2023 */
2024 final ArrayList<ActivityRecord> mRelaunchingActivities
2025 = new ArrayList<ActivityRecord>();
2026 Configuration mPendingConfiguration = null;
Bob Leee5408332009-09-04 18:31:17 -07002027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 // These can be accessed by multiple threads; mPackages is the lock.
2029 // XXX For now we keep around information about all packages we have
2030 // seen, not removing entries from this map.
2031 final HashMap<String, WeakReference<PackageInfo>> mPackages
2032 = new HashMap<String, WeakReference<PackageInfo>>();
2033 final HashMap<String, WeakReference<PackageInfo>> mResourcePackages
2034 = new HashMap<String, WeakReference<PackageInfo>>();
2035 Display mDisplay = null;
2036 DisplayMetrics mDisplayMetrics = null;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002037 HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
2038 = new HashMap<ResourcesKey, WeakReference<Resources> >();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039
2040 // The lock of mProviderMap protects the following variables.
2041 final HashMap<String, ProviderRecord> mProviderMap
2042 = new HashMap<String, ProviderRecord>();
2043 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
2044 = new HashMap<IBinder, ProviderRefCount>();
2045 final HashMap<IBinder, ProviderRecord> mLocalProviders
2046 = new HashMap<IBinder, ProviderRecord>();
2047
2048 final GcIdler mGcIdler = new GcIdler();
2049 boolean mGcIdlerScheduled = false;
2050
2051 public final PackageInfo getPackageInfo(String packageName, int flags) {
2052 synchronized (mPackages) {
2053 WeakReference<PackageInfo> ref;
2054 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
2055 ref = mPackages.get(packageName);
2056 } else {
2057 ref = mResourcePackages.get(packageName);
2058 }
2059 PackageInfo packageInfo = ref != null ? ref.get() : null;
2060 //Log.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
2061 if (packageInfo != null && (packageInfo.mResources == null
2062 || packageInfo.mResources.getAssets().isUpToDate())) {
2063 if (packageInfo.isSecurityViolation()
2064 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2065 throw new SecurityException(
2066 "Requesting code from " + packageName
2067 + " to be run in process "
2068 + mBoundApplication.processName
2069 + "/" + mBoundApplication.appInfo.uid);
2070 }
2071 return packageInfo;
2072 }
2073 }
2074
2075 ApplicationInfo ai = null;
2076 try {
2077 ai = getPackageManager().getApplicationInfo(packageName,
2078 PackageManager.GET_SHARED_LIBRARY_FILES);
2079 } catch (RemoteException e) {
2080 }
2081
2082 if (ai != null) {
2083 return getPackageInfo(ai, flags);
2084 }
2085
2086 return null;
2087 }
2088
2089 public final PackageInfo getPackageInfo(ApplicationInfo ai, int flags) {
2090 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2091 boolean securityViolation = includeCode && ai.uid != 0
2092 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
2093 ? ai.uid != mBoundApplication.appInfo.uid : true);
2094 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2095 |Context.CONTEXT_IGNORE_SECURITY))
2096 == Context.CONTEXT_INCLUDE_CODE) {
2097 if (securityViolation) {
2098 String msg = "Requesting code from " + ai.packageName
2099 + " (with uid " + ai.uid + ")";
2100 if (mBoundApplication != null) {
2101 msg = msg + " to be run in process "
2102 + mBoundApplication.processName + " (with uid "
2103 + mBoundApplication.appInfo.uid + ")";
2104 }
2105 throw new SecurityException(msg);
2106 }
2107 }
2108 return getPackageInfo(ai, null, securityViolation, includeCode);
2109 }
2110
2111 public final PackageInfo getPackageInfoNoCheck(ApplicationInfo ai) {
2112 return getPackageInfo(ai, null, false, true);
2113 }
2114
2115 private final PackageInfo getPackageInfo(ApplicationInfo aInfo,
2116 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
2117 synchronized (mPackages) {
2118 WeakReference<PackageInfo> ref;
2119 if (includeCode) {
2120 ref = mPackages.get(aInfo.packageName);
2121 } else {
2122 ref = mResourcePackages.get(aInfo.packageName);
2123 }
2124 PackageInfo packageInfo = ref != null ? ref.get() : null;
2125 if (packageInfo == null || (packageInfo.mResources != null
2126 && !packageInfo.mResources.getAssets().isUpToDate())) {
2127 if (localLOGV) Log.v(TAG, (includeCode ? "Loading code package "
2128 : "Loading resource-only package ") + aInfo.packageName
2129 + " (in " + (mBoundApplication != null
2130 ? mBoundApplication.processName : null)
2131 + ")");
2132 packageInfo =
2133 new PackageInfo(this, aInfo, this, baseLoader,
2134 securityViolation, includeCode &&
2135 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
2136 if (includeCode) {
2137 mPackages.put(aInfo.packageName,
2138 new WeakReference<PackageInfo>(packageInfo));
2139 } else {
2140 mResourcePackages.put(aInfo.packageName,
2141 new WeakReference<PackageInfo>(packageInfo));
2142 }
2143 }
2144 return packageInfo;
2145 }
2146 }
2147
2148 public final boolean hasPackageInfo(String packageName) {
2149 synchronized (mPackages) {
2150 WeakReference<PackageInfo> ref;
2151 ref = mPackages.get(packageName);
2152 if (ref != null && ref.get() != null) {
2153 return true;
2154 }
2155 ref = mResourcePackages.get(packageName);
2156 if (ref != null && ref.get() != null) {
2157 return true;
2158 }
2159 return false;
2160 }
2161 }
Bob Leee5408332009-09-04 18:31:17 -07002162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 ActivityThread() {
2164 }
2165
2166 public ApplicationThread getApplicationThread()
2167 {
2168 return mAppThread;
2169 }
2170
2171 public Instrumentation getInstrumentation()
2172 {
2173 return mInstrumentation;
2174 }
2175
2176 public Configuration getConfiguration() {
2177 return mConfiguration;
2178 }
2179
2180 public boolean isProfiling() {
2181 return mBoundApplication != null && mBoundApplication.profileFile != null;
2182 }
2183
2184 public String getProfileFilePath() {
2185 return mBoundApplication.profileFile;
2186 }
2187
2188 public Looper getLooper() {
2189 return mLooper;
2190 }
2191
2192 public Application getApplication() {
2193 return mInitialApplication;
2194 }
Bob Leee5408332009-09-04 18:31:17 -07002195
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002196 public String getProcessName() {
2197 return mBoundApplication.processName;
2198 }
Bob Leee5408332009-09-04 18:31:17 -07002199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 public ApplicationContext getSystemContext() {
2201 synchronized (this) {
2202 if (mSystemContext == null) {
2203 ApplicationContext context =
2204 ApplicationContext.createSystemContext(this);
Mike Cleron432b7132009-09-24 15:28:29 -07002205 PackageInfo info = new PackageInfo(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 context.init(info, null, this);
2207 context.getResources().updateConfiguration(
2208 getConfiguration(), getDisplayMetricsLocked(false));
2209 mSystemContext = context;
2210 //Log.i(TAG, "Created system resources " + context.getResources()
2211 // + ": " + context.getResources().getConfiguration());
2212 }
2213 }
2214 return mSystemContext;
2215 }
2216
Mike Cleron432b7132009-09-24 15:28:29 -07002217 public void installSystemApplicationInfo(ApplicationInfo info) {
2218 synchronized (this) {
2219 ApplicationContext context = getSystemContext();
2220 context.init(new PackageInfo(this, "android", context, info), null, this);
2221 }
2222 }
2223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 void scheduleGcIdler() {
2225 if (!mGcIdlerScheduled) {
2226 mGcIdlerScheduled = true;
2227 Looper.myQueue().addIdleHandler(mGcIdler);
2228 }
2229 mH.removeMessages(H.GC_WHEN_IDLE);
2230 }
2231
2232 void unscheduleGcIdler() {
2233 if (mGcIdlerScheduled) {
2234 mGcIdlerScheduled = false;
2235 Looper.myQueue().removeIdleHandler(mGcIdler);
2236 }
2237 mH.removeMessages(H.GC_WHEN_IDLE);
2238 }
2239
2240 void doGcIfNeeded() {
2241 mGcIdlerScheduled = false;
2242 final long now = SystemClock.uptimeMillis();
2243 //Log.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
2244 // + "m now=" + now);
2245 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
2246 //Log.i(TAG, "**** WE DO, WE DO WANT TO GC!");
2247 BinderInternal.forceGc("bg");
2248 }
2249 }
2250
2251 public final ActivityInfo resolveActivityInfo(Intent intent) {
2252 ActivityInfo aInfo = intent.resolveActivityInfo(
2253 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2254 if (aInfo == null) {
2255 // Throw an exception.
2256 Instrumentation.checkStartActivityResult(
2257 IActivityManager.START_CLASS_NOT_FOUND, intent);
2258 }
2259 return aInfo;
2260 }
Bob Leee5408332009-09-04 18:31:17 -07002261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
2264 Object lastNonConfigurationInstance) {
2265 ActivityRecord r = new ActivityRecord();
2266 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002267 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 r.intent = intent;
2269 r.state = state;
2270 r.parent = parent;
2271 r.embeddedID = id;
2272 r.activityInfo = activityInfo;
2273 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
2274 if (localLOGV) {
2275 ComponentName compname = intent.getComponent();
2276 String name;
2277 if (compname != null) {
2278 name = compname.toShortString();
2279 } else {
2280 name = "(Intent " + intent + ").getComponent() returned null";
2281 }
2282 Log.v(TAG, "Performing launch: action=" + intent.getAction()
2283 + ", comp=" + name
2284 + ", token=" + token);
2285 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07002286 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 }
2288
2289 public final Activity getActivity(IBinder token) {
2290 return mActivities.get(token).activity;
2291 }
2292
2293 public final void sendActivityResult(
2294 IBinder token, String id, int requestCode,
2295 int resultCode, Intent data) {
Chris Tate8a7dc172009-03-24 20:11:42 -07002296 if (DEBUG_RESULTS) Log.v(TAG, "sendActivityResult: id=" + id
2297 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2299 list.add(new ResultInfo(id, requestCode, resultCode, data));
2300 mAppThread.scheduleSendResult(token, list);
2301 }
2302
2303 // if the thread hasn't started yet, we don't have the handler, so just
2304 // save the messages until we're ready.
2305 private final void queueOrSendMessage(int what, Object obj) {
2306 queueOrSendMessage(what, obj, 0, 0);
2307 }
2308
2309 private final void queueOrSendMessage(int what, Object obj, int arg1) {
2310 queueOrSendMessage(what, obj, arg1, 0);
2311 }
2312
2313 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
2314 synchronized (this) {
2315 if (localLOGV) Log.v(
2316 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2317 + ": " + arg1 + " / " + obj);
2318 Message msg = Message.obtain();
2319 msg.what = what;
2320 msg.obj = obj;
2321 msg.arg1 = arg1;
2322 msg.arg2 = arg2;
2323 mH.sendMessage(msg);
2324 }
2325 }
2326
2327 final void scheduleContextCleanup(ApplicationContext context, String who,
2328 String what) {
2329 ContextCleanupInfo cci = new ContextCleanupInfo();
2330 cci.context = context;
2331 cci.who = who;
2332 cci.what = what;
2333 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
2334 }
2335
Christopher Tateb70f3df2009-04-07 16:07:59 -07002336 private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
2338
2339 ActivityInfo aInfo = r.activityInfo;
2340 if (r.packageInfo == null) {
2341 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
2342 Context.CONTEXT_INCLUDE_CODE);
2343 }
Bob Leee5408332009-09-04 18:31:17 -07002344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 ComponentName component = r.intent.getComponent();
2346 if (component == null) {
2347 component = r.intent.resolveActivity(
2348 mInitialApplication.getPackageManager());
2349 r.intent.setComponent(component);
2350 }
2351
2352 if (r.activityInfo.targetActivity != null) {
2353 component = new ComponentName(r.activityInfo.packageName,
2354 r.activityInfo.targetActivity);
2355 }
2356
2357 Activity activity = null;
2358 try {
2359 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
2360 activity = mInstrumentation.newActivity(
2361 cl, component.getClassName(), r.intent);
2362 r.intent.setExtrasClassLoader(cl);
2363 if (r.state != null) {
2364 r.state.setClassLoader(cl);
2365 }
2366 } catch (Exception e) {
2367 if (!mInstrumentation.onException(activity, e)) {
2368 throw new RuntimeException(
2369 "Unable to instantiate activity " + component
2370 + ": " + e.toString(), e);
2371 }
2372 }
2373
2374 try {
Christopher Tate181fafa2009-05-14 11:12:14 -07002375 Application app = r.packageInfo.makeApplication(false);
Bob Leee5408332009-09-04 18:31:17 -07002376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 if (localLOGV) Log.v(TAG, "Performing launch of " + r);
2378 if (localLOGV) Log.v(
2379 TAG, r + ": app=" + app
2380 + ", appName=" + app.getPackageName()
2381 + ", pkg=" + r.packageInfo.getPackageName()
2382 + ", comp=" + r.intent.getComponent().toShortString()
2383 + ", dir=" + r.packageInfo.getAppDir());
2384
2385 if (activity != null) {
2386 ApplicationContext appContext = new ApplicationContext();
2387 appContext.init(r.packageInfo, r.token, this);
2388 appContext.setOuterContext(activity);
2389 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
2390 Configuration config = new Configuration(mConfiguration);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002391 activity.attach(appContext, this, getInstrumentation(), r.token,
2392 r.ident, app, r.intent, r.activityInfo, title, r.parent,
2393 r.embeddedID, r.lastNonConfigurationInstance,
2394 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07002395
Christopher Tateb70f3df2009-04-07 16:07:59 -07002396 if (customIntent != null) {
2397 activity.mIntent = customIntent;
2398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 r.lastNonConfigurationInstance = null;
2400 r.lastNonConfigurationChildInstances = null;
2401 activity.mStartedActivity = false;
2402 int theme = r.activityInfo.getThemeResource();
2403 if (theme != 0) {
2404 activity.setTheme(theme);
2405 }
2406
2407 activity.mCalled = false;
2408 mInstrumentation.callActivityOnCreate(activity, r.state);
2409 if (!activity.mCalled) {
2410 throw new SuperNotCalledException(
2411 "Activity " + r.intent.getComponent().toShortString() +
2412 " did not call through to super.onCreate()");
2413 }
2414 r.activity = activity;
2415 r.stopped = true;
2416 if (!r.activity.mFinished) {
2417 activity.performStart();
2418 r.stopped = false;
2419 }
2420 if (!r.activity.mFinished) {
2421 if (r.state != null) {
2422 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2423 }
2424 }
2425 if (!r.activity.mFinished) {
2426 activity.mCalled = false;
2427 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2428 if (!activity.mCalled) {
2429 throw new SuperNotCalledException(
2430 "Activity " + r.intent.getComponent().toShortString() +
2431 " did not call through to super.onPostCreate()");
2432 }
2433 }
2434 r.state = null;
2435 }
2436 r.paused = true;
2437
2438 mActivities.put(r.token, r);
2439
2440 } catch (SuperNotCalledException e) {
2441 throw e;
2442
2443 } catch (Exception e) {
2444 if (!mInstrumentation.onException(activity, e)) {
2445 throw new RuntimeException(
2446 "Unable to start activity " + component
2447 + ": " + e.toString(), e);
2448 }
2449 }
2450
2451 return activity;
2452 }
2453
Christopher Tateb70f3df2009-04-07 16:07:59 -07002454 private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 // If we are getting ready to gc after going to the background, well
2456 // we are back active so skip it.
2457 unscheduleGcIdler();
2458
2459 if (localLOGV) Log.v(
2460 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002461 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462
2463 if (a != null) {
2464 handleResumeActivity(r.token, false, r.isForward);
2465
2466 if (!r.activity.mFinished && r.startsNotResumed) {
2467 // The activity manager actually wants this one to start out
2468 // paused, because it needs to be visible but isn't in the
2469 // foreground. We accomplish this by going through the
2470 // normal startup (because activities expect to go through
2471 // onResume() the first time they run, before their window
2472 // is displayed), and then pausing it. However, in this case
2473 // we do -not- need to do the full pause cycle (of freezing
2474 // and such) because the activity manager assumes it can just
2475 // retain the current state it has.
2476 try {
2477 r.activity.mCalled = false;
2478 mInstrumentation.callActivityOnPause(r.activity);
2479 if (!r.activity.mCalled) {
2480 throw new SuperNotCalledException(
2481 "Activity " + r.intent.getComponent().toShortString() +
2482 " did not call through to super.onPause()");
2483 }
2484
2485 } catch (SuperNotCalledException e) {
2486 throw e;
2487
2488 } catch (Exception e) {
2489 if (!mInstrumentation.onException(r.activity, e)) {
2490 throw new RuntimeException(
2491 "Unable to pause activity "
2492 + r.intent.getComponent().toShortString()
2493 + ": " + e.toString(), e);
2494 }
2495 }
2496 r.paused = true;
2497 }
2498 } else {
2499 // If there was an error, for any reason, tell the activity
2500 // manager to stop us.
2501 try {
2502 ActivityManagerNative.getDefault()
2503 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2504 } catch (RemoteException ex) {
2505 }
2506 }
2507 }
2508
2509 private final void deliverNewIntents(ActivityRecord r,
2510 List<Intent> intents) {
2511 final int N = intents.size();
2512 for (int i=0; i<N; i++) {
2513 Intent intent = intents.get(i);
2514 intent.setExtrasClassLoader(r.activity.getClassLoader());
2515 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2516 }
2517 }
2518
2519 public final void performNewIntents(IBinder token,
2520 List<Intent> intents) {
2521 ActivityRecord r = mActivities.get(token);
2522 if (r != null) {
2523 final boolean resumed = !r.paused;
2524 if (resumed) {
2525 mInstrumentation.callActivityOnPause(r.activity);
2526 }
2527 deliverNewIntents(r, intents);
2528 if (resumed) {
2529 mInstrumentation.callActivityOnResume(r.activity);
2530 }
2531 }
2532 }
Bob Leee5408332009-09-04 18:31:17 -07002533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 private final void handleNewIntent(NewIntentData data) {
2535 performNewIntents(data.token, data.intents);
2536 }
2537
2538 private final void handleReceiver(ReceiverData data) {
2539 // If we are getting ready to gc after going to the background, well
2540 // we are back active so skip it.
2541 unscheduleGcIdler();
2542
2543 String component = data.intent.getComponent().getClassName();
2544
2545 PackageInfo packageInfo = getPackageInfoNoCheck(
2546 data.info.applicationInfo);
2547
2548 IActivityManager mgr = ActivityManagerNative.getDefault();
2549
2550 BroadcastReceiver receiver = null;
2551 try {
2552 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2553 data.intent.setExtrasClassLoader(cl);
2554 if (data.resultExtras != null) {
2555 data.resultExtras.setClassLoader(cl);
2556 }
2557 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2558 } catch (Exception e) {
2559 try {
2560 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2561 data.resultData, data.resultExtras, data.resultAbort);
2562 } catch (RemoteException ex) {
2563 }
2564 throw new RuntimeException(
2565 "Unable to instantiate receiver " + component
2566 + ": " + e.toString(), e);
2567 }
2568
2569 try {
Christopher Tate181fafa2009-05-14 11:12:14 -07002570 Application app = packageInfo.makeApplication(false);
Bob Leee5408332009-09-04 18:31:17 -07002571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 if (localLOGV) Log.v(
2573 TAG, "Performing receive of " + data.intent
2574 + ": app=" + app
2575 + ", appName=" + app.getPackageName()
2576 + ", pkg=" + packageInfo.getPackageName()
2577 + ", comp=" + data.intent.getComponent().toShortString()
2578 + ", dir=" + packageInfo.getAppDir());
2579
2580 ApplicationContext context = (ApplicationContext)app.getBaseContext();
2581 receiver.setOrderedHint(true);
2582 receiver.setResult(data.resultCode, data.resultData,
2583 data.resultExtras);
2584 receiver.setOrderedHint(data.sync);
2585 receiver.onReceive(context.getReceiverRestrictedContext(),
2586 data.intent);
2587 } catch (Exception e) {
2588 try {
2589 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
2590 data.resultData, data.resultExtras, data.resultAbort);
2591 } catch (RemoteException ex) {
2592 }
2593 if (!mInstrumentation.onException(receiver, e)) {
2594 throw new RuntimeException(
2595 "Unable to start receiver " + component
2596 + ": " + e.toString(), e);
2597 }
2598 }
2599
2600 try {
2601 if (data.sync) {
2602 mgr.finishReceiver(
2603 mAppThread.asBinder(), receiver.getResultCode(),
2604 receiver.getResultData(), receiver.getResultExtras(false),
2605 receiver.getAbortBroadcast());
2606 } else {
2607 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
2608 }
2609 } catch (RemoteException ex) {
2610 }
2611 }
2612
Christopher Tate181fafa2009-05-14 11:12:14 -07002613 // Instantiate a BackupAgent and tell it that it's alive
2614 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
2615 if (DEBUG_BACKUP) Log.v(TAG, "handleCreateBackupAgent: " + data);
2616
2617 // no longer idle; we have backup work to do
2618 unscheduleGcIdler();
2619
2620 // instantiate the BackupAgent class named in the manifest
2621 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2622 String packageName = packageInfo.mPackageName;
2623 if (mBackupAgents.get(packageName) != null) {
2624 Log.d(TAG, "BackupAgent " + " for " + packageName
2625 + " already exists");
2626 return;
2627 }
Bob Leee5408332009-09-04 18:31:17 -07002628
Christopher Tate181fafa2009-05-14 11:12:14 -07002629 BackupAgent agent = null;
2630 String classname = data.appInfo.backupAgentName;
2631 if (classname == null) {
2632 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
2633 Log.e(TAG, "Attempted incremental backup but no defined agent for "
2634 + packageName);
2635 return;
2636 }
2637 classname = "android.app.FullBackupAgent";
2638 }
2639 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002640 IBinder binder = null;
2641 try {
2642 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2643 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
2644
2645 // set up the agent's context
2646 if (DEBUG_BACKUP) Log.v(TAG, "Initializing BackupAgent "
2647 + data.appInfo.backupAgentName);
2648
2649 ApplicationContext context = new ApplicationContext();
2650 context.init(packageInfo, null, this);
2651 context.setOuterContext(agent);
2652 agent.attach(context);
2653
2654 agent.onCreate();
2655 binder = agent.onBind();
2656 mBackupAgents.put(packageName, agent);
2657 } catch (Exception e) {
2658 // If this is during restore, fail silently; otherwise go
2659 // ahead and let the user see the crash.
2660 Log.e(TAG, "Agent threw during creation: " + e);
2661 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
2662 throw e;
2663 }
2664 // falling through with 'binder' still null
2665 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002666
2667 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002668 try {
2669 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2670 } catch (RemoteException e) {
2671 // nothing to do.
2672 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002673 } catch (Exception e) {
2674 throw new RuntimeException("Unable to create BackupAgent "
2675 + data.appInfo.backupAgentName + ": " + e.toString(), e);
2676 }
2677 }
2678
2679 // Tear down a BackupAgent
2680 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
2681 if (DEBUG_BACKUP) Log.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002682
Christopher Tate181fafa2009-05-14 11:12:14 -07002683 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo);
2684 String packageName = packageInfo.mPackageName;
2685 BackupAgent agent = mBackupAgents.get(packageName);
2686 if (agent != null) {
2687 try {
2688 agent.onDestroy();
2689 } catch (Exception e) {
2690 Log.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
2691 e.printStackTrace();
2692 }
2693 mBackupAgents.remove(packageName);
2694 } else {
2695 Log.w(TAG, "Attempt to destroy unknown backup agent " + data);
2696 }
2697 }
2698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 private final void handleCreateService(CreateServiceData data) {
2700 // If we are getting ready to gc after going to the background, well
2701 // we are back active so skip it.
2702 unscheduleGcIdler();
2703
2704 PackageInfo packageInfo = getPackageInfoNoCheck(
2705 data.info.applicationInfo);
2706 Service service = null;
2707 try {
2708 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2709 service = (Service) cl.loadClass(data.info.name).newInstance();
2710 } catch (Exception e) {
2711 if (!mInstrumentation.onException(service, e)) {
2712 throw new RuntimeException(
2713 "Unable to instantiate service " + data.info.name
2714 + ": " + e.toString(), e);
2715 }
2716 }
2717
2718 try {
2719 if (localLOGV) Log.v(TAG, "Creating service " + data.info.name);
2720
2721 ApplicationContext context = new ApplicationContext();
2722 context.init(packageInfo, null, this);
2723
Christopher Tate181fafa2009-05-14 11:12:14 -07002724 Application app = packageInfo.makeApplication(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 context.setOuterContext(service);
2726 service.attach(context, this, data.info.name, data.token, app,
2727 ActivityManagerNative.getDefault());
2728 service.onCreate();
2729 mServices.put(data.token, service);
2730 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002731 ActivityManagerNative.getDefault().serviceDoneExecuting(
2732 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 } catch (RemoteException e) {
2734 // nothing to do.
2735 }
2736 } catch (Exception e) {
2737 if (!mInstrumentation.onException(service, e)) {
2738 throw new RuntimeException(
2739 "Unable to create service " + data.info.name
2740 + ": " + e.toString(), e);
2741 }
2742 }
2743 }
2744
2745 private final void handleBindService(BindServiceData data) {
2746 Service s = mServices.get(data.token);
2747 if (s != null) {
2748 try {
2749 data.intent.setExtrasClassLoader(s.getClassLoader());
2750 try {
2751 if (!data.rebind) {
2752 IBinder binder = s.onBind(data.intent);
2753 ActivityManagerNative.getDefault().publishService(
2754 data.token, data.intent, binder);
2755 } else {
2756 s.onRebind(data.intent);
2757 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002758 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 }
2760 } catch (RemoteException ex) {
2761 }
2762 } catch (Exception e) {
2763 if (!mInstrumentation.onException(s, e)) {
2764 throw new RuntimeException(
2765 "Unable to bind to service " + s
2766 + " with " + data.intent + ": " + e.toString(), e);
2767 }
2768 }
2769 }
2770 }
2771
2772 private final void handleUnbindService(BindServiceData data) {
2773 Service s = mServices.get(data.token);
2774 if (s != null) {
2775 try {
2776 data.intent.setExtrasClassLoader(s.getClassLoader());
2777 boolean doRebind = s.onUnbind(data.intent);
2778 try {
2779 if (doRebind) {
2780 ActivityManagerNative.getDefault().unbindFinished(
2781 data.token, data.intent, doRebind);
2782 } else {
2783 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002784 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 }
2786 } catch (RemoteException ex) {
2787 }
2788 } catch (Exception e) {
2789 if (!mInstrumentation.onException(s, e)) {
2790 throw new RuntimeException(
2791 "Unable to unbind to service " + s
2792 + " with " + data.intent + ": " + e.toString(), e);
2793 }
2794 }
2795 }
2796 }
2797
2798 private void handleDumpService(DumpServiceInfo info) {
2799 try {
2800 Service s = mServices.get(info.service);
2801 if (s != null) {
2802 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2803 s.dump(info.fd, pw, info.args);
2804 pw.close();
2805 }
2806 } finally {
2807 synchronized (info) {
2808 info.dumped = true;
2809 info.notifyAll();
2810 }
2811 }
2812 }
2813
2814 private final void handleServiceArgs(ServiceArgsData data) {
2815 Service s = mServices.get(data.token);
2816 if (s != null) {
2817 try {
2818 if (data.args != null) {
2819 data.args.setExtrasClassLoader(s.getClassLoader());
2820 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002821 int res = s.onStartCommand(data.args, data.flags, data.startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002823 ActivityManagerNative.getDefault().serviceDoneExecuting(
2824 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 } catch (RemoteException e) {
2826 // nothing to do.
2827 }
2828 } catch (Exception e) {
2829 if (!mInstrumentation.onException(s, e)) {
2830 throw new RuntimeException(
2831 "Unable to start service " + s
2832 + " with " + data.args + ": " + e.toString(), e);
2833 }
2834 }
2835 }
2836 }
2837
2838 private final void handleStopService(IBinder token) {
2839 Service s = mServices.remove(token);
2840 if (s != null) {
2841 try {
2842 if (localLOGV) Log.v(TAG, "Destroying service " + s);
2843 s.onDestroy();
2844 Context context = s.getBaseContext();
2845 if (context instanceof ApplicationContext) {
2846 final String who = s.getClassName();
2847 ((ApplicationContext) context).scheduleFinalCleanup(who, "Service");
2848 }
2849 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002850 ActivityManagerNative.getDefault().serviceDoneExecuting(
2851 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 } catch (RemoteException e) {
2853 // nothing to do.
2854 }
2855 } catch (Exception e) {
2856 if (!mInstrumentation.onException(s, e)) {
2857 throw new RuntimeException(
2858 "Unable to stop service " + s
2859 + ": " + e.toString(), e);
2860 }
2861 }
2862 }
2863 //Log.i(TAG, "Running services: " + mServices);
2864 }
2865
2866 public final ActivityRecord performResumeActivity(IBinder token,
2867 boolean clearHide) {
2868 ActivityRecord r = mActivities.get(token);
2869 if (localLOGV) Log.v(TAG, "Performing resume of " + r
2870 + " finished=" + r.activity.mFinished);
2871 if (r != null && !r.activity.mFinished) {
2872 if (clearHide) {
2873 r.hideForNow = false;
2874 r.activity.mStartedActivity = false;
2875 }
2876 try {
2877 if (r.pendingIntents != null) {
2878 deliverNewIntents(r, r.pendingIntents);
2879 r.pendingIntents = null;
2880 }
2881 if (r.pendingResults != null) {
2882 deliverResults(r, r.pendingResults);
2883 r.pendingResults = null;
2884 }
2885 r.activity.performResume();
2886
Bob Leee5408332009-09-04 18:31:17 -07002887 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 r.paused = false;
2891 r.stopped = false;
2892 if (r.activity.mStartedActivity) {
2893 r.hideForNow = true;
2894 }
2895 r.state = null;
2896 } catch (Exception e) {
2897 if (!mInstrumentation.onException(r.activity, e)) {
2898 throw new RuntimeException(
2899 "Unable to resume activity "
2900 + r.intent.getComponent().toShortString()
2901 + ": " + e.toString(), e);
2902 }
2903 }
2904 }
2905 return r;
2906 }
2907
2908 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2909 // If we are getting ready to gc after going to the background, well
2910 // we are back active so skip it.
2911 unscheduleGcIdler();
2912
2913 ActivityRecord r = performResumeActivity(token, clearHide);
2914
2915 if (r != null) {
2916 final Activity a = r.activity;
2917
2918 if (localLOGV) Log.v(
2919 TAG, "Resume " + r + " started activity: " +
2920 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2921 + ", finished: " + a.mFinished);
2922
2923 final int forwardBit = isForward ?
2924 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 // If the window hasn't yet been added to the window manager,
2927 // and this guy didn't finish itself or start another activity,
2928 // then go ahead and add the window.
2929 if (r.window == null && !a.mFinished && !a.mStartedActivity) {
2930 r.window = r.activity.getWindow();
2931 View decor = r.window.getDecorView();
2932 decor.setVisibility(View.INVISIBLE);
2933 ViewManager wm = a.getWindowManager();
2934 WindowManager.LayoutParams l = r.window.getAttributes();
2935 a.mDecor = decor;
2936 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2937 l.softInputMode |= forwardBit;
2938 if (a.mVisibleFromClient) {
2939 a.mWindowAdded = true;
2940 wm.addView(decor, l);
2941 }
2942
2943 // If the window has already been added, but during resume
2944 // we started another activity, then don't yet make the
2945 // window visisble.
2946 } else if (a.mStartedActivity) {
2947 if (localLOGV) Log.v(
2948 TAG, "Launch " + r + " mStartedActivity set");
2949 r.hideForNow = true;
2950 }
2951
2952 // The window is now visible if it has been added, we are not
2953 // simply finishing, and we are not starting another activity.
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002954 if (!r.activity.mFinished && !a.mStartedActivity
2955 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 if (r.newConfig != null) {
2957 performConfigurationChanged(r.activity, r.newConfig);
2958 r.newConfig = null;
2959 }
2960 if (localLOGV) Log.v(TAG, "Resuming " + r + " with isForward="
2961 + isForward);
2962 WindowManager.LayoutParams l = r.window.getAttributes();
2963 if ((l.softInputMode
2964 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2965 != forwardBit) {
2966 l.softInputMode = (l.softInputMode
2967 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2968 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002969 if (r.activity.mVisibleFromClient) {
2970 ViewManager wm = a.getWindowManager();
2971 View decor = r.window.getDecorView();
2972 wm.updateViewLayout(decor, l);
2973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
2975 r.activity.mVisibleFromServer = true;
2976 mNumVisibleActivities++;
2977 if (r.activity.mVisibleFromClient) {
2978 r.activity.makeVisible();
2979 }
2980 }
2981
2982 r.nextIdle = mNewActivities;
2983 mNewActivities = r;
2984 if (localLOGV) Log.v(
2985 TAG, "Scheduling idle handler for " + r);
2986 Looper.myQueue().addIdleHandler(new Idler());
2987
2988 } else {
2989 // If an exception was thrown when trying to resume, then
2990 // just end this activity.
2991 try {
2992 ActivityManagerNative.getDefault()
2993 .finishActivity(token, Activity.RESULT_CANCELED, null);
2994 } catch (RemoteException ex) {
2995 }
2996 }
2997 }
2998
2999 private int mThumbnailWidth = -1;
3000 private int mThumbnailHeight = -1;
3001
3002 private final Bitmap createThumbnailBitmap(ActivityRecord r) {
3003 Bitmap thumbnail = null;
3004 try {
3005 int w = mThumbnailWidth;
3006 int h;
3007 if (w < 0) {
3008 Resources res = r.activity.getResources();
3009 mThumbnailHeight = h =
3010 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
3011
3012 mThumbnailWidth = w =
3013 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
3014 } else {
3015 h = mThumbnailHeight;
3016 }
3017
3018 // XXX Only set hasAlpha if needed?
3019 thumbnail = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
3020 thumbnail.eraseColor(0);
3021 Canvas cv = new Canvas(thumbnail);
3022 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
3023 thumbnail = null;
3024 }
3025 } catch (Exception e) {
3026 if (!mInstrumentation.onException(r.activity, e)) {
3027 throw new RuntimeException(
3028 "Unable to create thumbnail of "
3029 + r.intent.getComponent().toShortString()
3030 + ": " + e.toString(), e);
3031 }
3032 thumbnail = null;
3033 }
3034
3035 return thumbnail;
3036 }
3037
3038 private final void handlePauseActivity(IBinder token, boolean finished,
3039 boolean userLeaving, int configChanges) {
3040 ActivityRecord r = mActivities.get(token);
3041 if (r != null) {
3042 //Log.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
3043 if (userLeaving) {
3044 performUserLeavingActivity(r);
3045 }
Bob Leee5408332009-09-04 18:31:17 -07003046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 r.activity.mConfigChangeFlags |= configChanges;
3048 Bundle state = performPauseActivity(token, finished, true);
3049
3050 // Tell the activity manager we have paused.
3051 try {
3052 ActivityManagerNative.getDefault().activityPaused(token, state);
3053 } catch (RemoteException ex) {
3054 }
3055 }
3056 }
3057
3058 final void performUserLeavingActivity(ActivityRecord r) {
3059 mInstrumentation.callActivityOnUserLeaving(r.activity);
3060 }
3061
3062 final Bundle performPauseActivity(IBinder token, boolean finished,
3063 boolean saveState) {
3064 ActivityRecord r = mActivities.get(token);
3065 return r != null ? performPauseActivity(r, finished, saveState) : null;
3066 }
3067
3068 final Bundle performPauseActivity(ActivityRecord r, boolean finished,
3069 boolean saveState) {
3070 if (r.paused) {
3071 if (r.activity.mFinished) {
3072 // If we are finishing, we won't call onResume() in certain cases.
3073 // So here we likewise don't want to call onPause() if the activity
3074 // isn't resumed.
3075 return null;
3076 }
3077 RuntimeException e = new RuntimeException(
3078 "Performing pause of activity that is not resumed: "
3079 + r.intent.getComponent().toShortString());
3080 Log.e(TAG, e.getMessage(), e);
3081 }
3082 Bundle state = null;
3083 if (finished) {
3084 r.activity.mFinished = true;
3085 }
3086 try {
3087 // Next have the activity save its current state and managed dialogs...
3088 if (!r.activity.mFinished && saveState) {
3089 state = new Bundle();
3090 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
3091 r.state = state;
3092 }
3093 // Now we are idle.
3094 r.activity.mCalled = false;
3095 mInstrumentation.callActivityOnPause(r.activity);
3096 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
3097 if (!r.activity.mCalled) {
3098 throw new SuperNotCalledException(
3099 "Activity " + r.intent.getComponent().toShortString() +
3100 " did not call through to super.onPause()");
3101 }
3102
3103 } catch (SuperNotCalledException e) {
3104 throw e;
3105
3106 } catch (Exception e) {
3107 if (!mInstrumentation.onException(r.activity, e)) {
3108 throw new RuntimeException(
3109 "Unable to pause activity "
3110 + r.intent.getComponent().toShortString()
3111 + ": " + e.toString(), e);
3112 }
3113 }
3114 r.paused = true;
3115 return state;
3116 }
3117
3118 final void performStopActivity(IBinder token) {
3119 ActivityRecord r = mActivities.get(token);
3120 performStopActivityInner(r, null, false);
3121 }
3122
3123 private static class StopInfo {
3124 Bitmap thumbnail;
3125 CharSequence description;
3126 }
3127
3128 private final class ProviderRefCount {
3129 public int count;
3130 ProviderRefCount(int pCount) {
3131 count = pCount;
3132 }
3133 }
3134
3135 private final void performStopActivityInner(ActivityRecord r,
3136 StopInfo info, boolean keepShown) {
3137 if (localLOGV) Log.v(TAG, "Performing stop of " + r);
3138 if (r != null) {
3139 if (!keepShown && r.stopped) {
3140 if (r.activity.mFinished) {
3141 // If we are finishing, we won't call onResume() in certain
3142 // cases. So here we likewise don't want to call onStop()
3143 // if the activity isn't resumed.
3144 return;
3145 }
3146 RuntimeException e = new RuntimeException(
3147 "Performing stop of activity that is not resumed: "
3148 + r.intent.getComponent().toShortString());
3149 Log.e(TAG, e.getMessage(), e);
3150 }
3151
3152 if (info != null) {
3153 try {
3154 // First create a thumbnail for the activity...
3155 //info.thumbnail = createThumbnailBitmap(r);
3156 info.description = r.activity.onCreateDescription();
3157 } catch (Exception e) {
3158 if (!mInstrumentation.onException(r.activity, e)) {
3159 throw new RuntimeException(
3160 "Unable to save state of activity "
3161 + r.intent.getComponent().toShortString()
3162 + ": " + e.toString(), e);
3163 }
3164 }
3165 }
3166
3167 if (!keepShown) {
3168 try {
3169 // Now we are idle.
3170 r.activity.performStop();
3171 } catch (Exception e) {
3172 if (!mInstrumentation.onException(r.activity, e)) {
3173 throw new RuntimeException(
3174 "Unable to stop activity "
3175 + r.intent.getComponent().toShortString()
3176 + ": " + e.toString(), e);
3177 }
3178 }
3179 r.stopped = true;
3180 }
3181
3182 r.paused = true;
3183 }
3184 }
3185
3186 private final void updateVisibility(ActivityRecord r, boolean show) {
3187 View v = r.activity.mDecor;
3188 if (v != null) {
3189 if (show) {
3190 if (!r.activity.mVisibleFromServer) {
3191 r.activity.mVisibleFromServer = true;
3192 mNumVisibleActivities++;
3193 if (r.activity.mVisibleFromClient) {
3194 r.activity.makeVisible();
3195 }
3196 }
3197 if (r.newConfig != null) {
3198 performConfigurationChanged(r.activity, r.newConfig);
3199 r.newConfig = null;
3200 }
3201 } else {
3202 if (r.activity.mVisibleFromServer) {
3203 r.activity.mVisibleFromServer = false;
3204 mNumVisibleActivities--;
3205 v.setVisibility(View.INVISIBLE);
3206 }
3207 }
3208 }
3209 }
3210
3211 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
3212 ActivityRecord r = mActivities.get(token);
3213 r.activity.mConfigChangeFlags |= configChanges;
3214
3215 StopInfo info = new StopInfo();
3216 performStopActivityInner(r, info, show);
3217
3218 if (localLOGV) Log.v(
3219 TAG, "Finishing stop of " + r + ": show=" + show
3220 + " win=" + r.window);
3221
3222 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07003223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 // Tell activity manager we have been stopped.
3225 try {
3226 ActivityManagerNative.getDefault().activityStopped(
3227 r.token, info.thumbnail, info.description);
3228 } catch (RemoteException ex) {
3229 }
3230 }
3231
3232 final void performRestartActivity(IBinder token) {
3233 ActivityRecord r = mActivities.get(token);
3234 if (r.stopped) {
3235 r.activity.performRestart();
3236 r.stopped = false;
3237 }
3238 }
3239
3240 private final void handleWindowVisibility(IBinder token, boolean show) {
3241 ActivityRecord r = mActivities.get(token);
3242 if (!show && !r.stopped) {
3243 performStopActivityInner(r, null, show);
3244 } else if (show && r.stopped) {
3245 // If we are getting ready to gc after going to the background, well
3246 // we are back active so skip it.
3247 unscheduleGcIdler();
3248
3249 r.activity.performRestart();
3250 r.stopped = false;
3251 }
3252 if (r.activity.mDecor != null) {
3253 if (Config.LOGV) Log.v(
3254 TAG, "Handle window " + r + " visibility: " + show);
3255 updateVisibility(r, show);
3256 }
3257 }
3258
3259 private final void deliverResults(ActivityRecord r, List<ResultInfo> results) {
3260 final int N = results.size();
3261 for (int i=0; i<N; i++) {
3262 ResultInfo ri = results.get(i);
3263 try {
3264 if (ri.mData != null) {
3265 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3266 }
Chris Tate8a7dc172009-03-24 20:11:42 -07003267 if (DEBUG_RESULTS) Log.v(TAG,
3268 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 r.activity.dispatchActivityResult(ri.mResultWho,
3270 ri.mRequestCode, ri.mResultCode, ri.mData);
3271 } catch (Exception e) {
3272 if (!mInstrumentation.onException(r.activity, e)) {
3273 throw new RuntimeException(
3274 "Failure delivering result " + ri + " to activity "
3275 + r.intent.getComponent().toShortString()
3276 + ": " + e.toString(), e);
3277 }
3278 }
3279 }
3280 }
3281
3282 private final void handleSendResult(ResultData res) {
3283 ActivityRecord r = mActivities.get(res.token);
Chris Tate8a7dc172009-03-24 20:11:42 -07003284 if (DEBUG_RESULTS) Log.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 if (r != null) {
3286 final boolean resumed = !r.paused;
3287 if (!r.activity.mFinished && r.activity.mDecor != null
3288 && r.hideForNow && resumed) {
3289 // We had hidden the activity because it started another
3290 // one... we have gotten a result back and we are not
3291 // paused, so make sure our window is visible.
3292 updateVisibility(r, true);
3293 }
3294 if (resumed) {
3295 try {
3296 // Now we are idle.
3297 r.activity.mCalled = false;
3298 mInstrumentation.callActivityOnPause(r.activity);
3299 if (!r.activity.mCalled) {
3300 throw new SuperNotCalledException(
3301 "Activity " + r.intent.getComponent().toShortString()
3302 + " did not call through to super.onPause()");
3303 }
3304 } catch (SuperNotCalledException e) {
3305 throw e;
3306 } catch (Exception e) {
3307 if (!mInstrumentation.onException(r.activity, e)) {
3308 throw new RuntimeException(
3309 "Unable to pause activity "
3310 + r.intent.getComponent().toShortString()
3311 + ": " + e.toString(), e);
3312 }
3313 }
3314 }
3315 deliverResults(r, res.results);
3316 if (resumed) {
3317 mInstrumentation.callActivityOnResume(r.activity);
3318 }
3319 }
3320 }
3321
3322 public final ActivityRecord performDestroyActivity(IBinder token, boolean finishing) {
3323 return performDestroyActivity(token, finishing, 0, false);
3324 }
3325
3326 private final ActivityRecord performDestroyActivity(IBinder token, boolean finishing,
3327 int configChanges, boolean getNonConfigInstance) {
3328 ActivityRecord r = mActivities.get(token);
3329 if (localLOGV) Log.v(TAG, "Performing finish of " + r);
3330 if (r != null) {
3331 r.activity.mConfigChangeFlags |= configChanges;
3332 if (finishing) {
3333 r.activity.mFinished = true;
3334 }
3335 if (!r.paused) {
3336 try {
3337 r.activity.mCalled = false;
3338 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003339 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 r.activity.getComponentName().getClassName());
3341 if (!r.activity.mCalled) {
3342 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003343 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 + " did not call through to super.onPause()");
3345 }
3346 } catch (SuperNotCalledException e) {
3347 throw e;
3348 } catch (Exception e) {
3349 if (!mInstrumentation.onException(r.activity, e)) {
3350 throw new RuntimeException(
3351 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003352 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 + ": " + e.toString(), e);
3354 }
3355 }
3356 r.paused = true;
3357 }
3358 if (!r.stopped) {
3359 try {
3360 r.activity.performStop();
3361 } catch (SuperNotCalledException e) {
3362 throw e;
3363 } catch (Exception e) {
3364 if (!mInstrumentation.onException(r.activity, e)) {
3365 throw new RuntimeException(
3366 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003367 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 + ": " + e.toString(), e);
3369 }
3370 }
3371 r.stopped = true;
3372 }
3373 if (getNonConfigInstance) {
3374 try {
3375 r.lastNonConfigurationInstance
3376 = r.activity.onRetainNonConfigurationInstance();
3377 } catch (Exception e) {
3378 if (!mInstrumentation.onException(r.activity, e)) {
3379 throw new RuntimeException(
3380 "Unable to retain activity "
3381 + r.intent.getComponent().toShortString()
3382 + ": " + e.toString(), e);
3383 }
3384 }
3385 try {
3386 r.lastNonConfigurationChildInstances
3387 = r.activity.onRetainNonConfigurationChildInstances();
3388 } catch (Exception e) {
3389 if (!mInstrumentation.onException(r.activity, e)) {
3390 throw new RuntimeException(
3391 "Unable to retain child activities "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003392 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 + ": " + e.toString(), e);
3394 }
3395 }
Bob Leee5408332009-09-04 18:31:17 -07003396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 }
3398 try {
3399 r.activity.mCalled = false;
3400 r.activity.onDestroy();
3401 if (!r.activity.mCalled) {
3402 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003403 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 " did not call through to super.onDestroy()");
3405 }
3406 if (r.window != null) {
3407 r.window.closeAllPanels();
3408 }
3409 } catch (SuperNotCalledException e) {
3410 throw e;
3411 } catch (Exception e) {
3412 if (!mInstrumentation.onException(r.activity, e)) {
3413 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003414 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3415 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 }
3417 }
3418 }
3419 mActivities.remove(token);
3420
3421 return r;
3422 }
3423
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003424 private static String safeToComponentShortString(Intent intent) {
3425 ComponentName component = intent.getComponent();
3426 return component == null ? "[Unknown]" : component.toShortString();
3427 }
3428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 private final void handleDestroyActivity(IBinder token, boolean finishing,
3430 int configChanges, boolean getNonConfigInstance) {
3431 ActivityRecord r = performDestroyActivity(token, finishing,
3432 configChanges, getNonConfigInstance);
3433 if (r != null) {
3434 WindowManager wm = r.activity.getWindowManager();
3435 View v = r.activity.mDecor;
3436 if (v != null) {
3437 if (r.activity.mVisibleFromServer) {
3438 mNumVisibleActivities--;
3439 }
3440 IBinder wtoken = v.getWindowToken();
3441 if (r.activity.mWindowAdded) {
3442 wm.removeViewImmediate(v);
3443 }
3444 if (wtoken != null) {
3445 WindowManagerImpl.getDefault().closeAll(wtoken,
3446 r.activity.getClass().getName(), "Activity");
3447 }
3448 r.activity.mDecor = null;
3449 }
3450 WindowManagerImpl.getDefault().closeAll(token,
3451 r.activity.getClass().getName(), "Activity");
3452
3453 // Mocked out contexts won't be participating in the normal
3454 // process lifecycle, but if we're running with a proper
3455 // ApplicationContext we need to have it tear down things
3456 // cleanly.
3457 Context c = r.activity.getBaseContext();
3458 if (c instanceof ApplicationContext) {
3459 ((ApplicationContext) c).scheduleFinalCleanup(
3460 r.activity.getClass().getName(), "Activity");
3461 }
3462 }
3463 if (finishing) {
3464 try {
3465 ActivityManagerNative.getDefault().activityDestroyed(token);
3466 } catch (RemoteException ex) {
3467 // If the system process has died, it's game over for everyone.
3468 }
3469 }
3470 }
3471
3472 private final void handleRelaunchActivity(ActivityRecord tmp, int configChanges) {
3473 // If we are getting ready to gc after going to the background, well
3474 // we are back active so skip it.
3475 unscheduleGcIdler();
3476
3477 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07003478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 // First: make sure we have the most recent configuration and most
3480 // recent version of the activity, or skip it if some previous call
3481 // had taken a more recent version.
3482 synchronized (mRelaunchingActivities) {
3483 int N = mRelaunchingActivities.size();
3484 IBinder token = tmp.token;
3485 tmp = null;
3486 for (int i=0; i<N; i++) {
3487 ActivityRecord r = mRelaunchingActivities.get(i);
3488 if (r.token == token) {
3489 tmp = r;
3490 mRelaunchingActivities.remove(i);
3491 i--;
3492 N--;
3493 }
3494 }
Bob Leee5408332009-09-04 18:31:17 -07003495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 if (tmp == null) {
3497 return;
3498 }
Bob Leee5408332009-09-04 18:31:17 -07003499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 if (mPendingConfiguration != null) {
3501 changedConfig = mPendingConfiguration;
3502 mPendingConfiguration = null;
3503 }
3504 }
Bob Leee5408332009-09-04 18:31:17 -07003505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 // If there was a pending configuration change, execute it first.
3507 if (changedConfig != null) {
3508 handleConfigurationChanged(changedConfig);
3509 }
Bob Leee5408332009-09-04 18:31:17 -07003510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 ActivityRecord r = mActivities.get(tmp.token);
3512 if (localLOGV) Log.v(TAG, "Handling relaunch of " + r);
3513 if (r == null) {
3514 return;
3515 }
Bob Leee5408332009-09-04 18:31:17 -07003516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003518 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 Bundle savedState = null;
3521 if (!r.paused) {
3522 savedState = performPauseActivity(r.token, false, true);
3523 }
Bob Leee5408332009-09-04 18:31:17 -07003524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 r.activity = null;
3528 r.window = null;
3529 r.hideForNow = false;
3530 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003531 // Merge any pending results and pending intents; don't just replace them
3532 if (tmp.pendingResults != null) {
3533 if (r.pendingResults == null) {
3534 r.pendingResults = tmp.pendingResults;
3535 } else {
3536 r.pendingResults.addAll(tmp.pendingResults);
3537 }
3538 }
3539 if (tmp.pendingIntents != null) {
3540 if (r.pendingIntents == null) {
3541 r.pendingIntents = tmp.pendingIntents;
3542 } else {
3543 r.pendingIntents.addAll(tmp.pendingIntents);
3544 }
3545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 r.startsNotResumed = tmp.startsNotResumed;
3547 if (savedState != null) {
3548 r.state = savedState;
3549 }
Bob Leee5408332009-09-04 18:31:17 -07003550
Christopher Tateb70f3df2009-04-07 16:07:59 -07003551 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 }
3553
3554 private final void handleRequestThumbnail(IBinder token) {
3555 ActivityRecord r = mActivities.get(token);
3556 Bitmap thumbnail = createThumbnailBitmap(r);
3557 CharSequence description = null;
3558 try {
3559 description = r.activity.onCreateDescription();
3560 } catch (Exception e) {
3561 if (!mInstrumentation.onException(r.activity, e)) {
3562 throw new RuntimeException(
3563 "Unable to create description of activity "
3564 + r.intent.getComponent().toShortString()
3565 + ": " + e.toString(), e);
3566 }
3567 }
3568 //System.out.println("Reporting top thumbnail " + thumbnail);
3569 try {
3570 ActivityManagerNative.getDefault().reportThumbnail(
3571 token, thumbnail, description);
3572 } catch (RemoteException ex) {
3573 }
3574 }
3575
3576 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
3577 boolean allActivities, Configuration newConfig) {
3578 ArrayList<ComponentCallbacks> callbacks
3579 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 if (mActivities.size() > 0) {
3582 Iterator<ActivityRecord> it = mActivities.values().iterator();
3583 while (it.hasNext()) {
3584 ActivityRecord ar = it.next();
3585 Activity a = ar.activity;
3586 if (a != null) {
3587 if (!ar.activity.mFinished && (allActivities ||
3588 (a != null && !ar.paused))) {
3589 // If the activity is currently resumed, its configuration
3590 // needs to change right now.
3591 callbacks.add(a);
3592 } else if (newConfig != null) {
3593 // Otherwise, we will tell it about the change
3594 // the next time it is resumed or shown. Note that
3595 // the activity manager may, before then, decide the
3596 // activity needs to be destroyed to handle its new
3597 // configuration.
3598 ar.newConfig = newConfig;
3599 }
3600 }
3601 }
3602 }
3603 if (mServices.size() > 0) {
3604 Iterator<Service> it = mServices.values().iterator();
3605 while (it.hasNext()) {
3606 callbacks.add(it.next());
3607 }
3608 }
3609 synchronized (mProviderMap) {
3610 if (mLocalProviders.size() > 0) {
3611 Iterator<ProviderRecord> it = mLocalProviders.values().iterator();
3612 while (it.hasNext()) {
3613 callbacks.add(it.next().mLocalProvider);
3614 }
3615 }
3616 }
3617 final int N = mAllApplications.size();
3618 for (int i=0; i<N; i++) {
3619 callbacks.add(mAllApplications.get(i));
3620 }
Bob Leee5408332009-09-04 18:31:17 -07003621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 return callbacks;
3623 }
Bob Leee5408332009-09-04 18:31:17 -07003624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 private final void performConfigurationChanged(
3626 ComponentCallbacks cb, Configuration config) {
3627 // Only for Activity objects, check that they actually call up to their
3628 // superclass implementation. ComponentCallbacks is an interface, so
3629 // we check the runtime type and act accordingly.
3630 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3631 if (activity != null) {
3632 activity.mCalled = false;
3633 }
Bob Leee5408332009-09-04 18:31:17 -07003634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 boolean shouldChangeConfig = false;
3636 if ((activity == null) || (activity.mCurrentConfig == null)) {
3637 shouldChangeConfig = true;
3638 } else {
Bob Leee5408332009-09-04 18:31:17 -07003639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 // If the new config is the same as the config this Activity
3641 // is already running with then don't bother calling
3642 // onConfigurationChanged
3643 int diff = activity.mCurrentConfig.diff(config);
3644 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07003645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003646 // If this activity doesn't handle any of the config changes
3647 // then don't bother calling onConfigurationChanged as we're
3648 // going to destroy it.
3649 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
3650 shouldChangeConfig = true;
3651 }
3652 }
3653 }
Bob Leee5408332009-09-04 18:31:17 -07003654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 if (shouldChangeConfig) {
3656 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 if (activity != null) {
3659 if (!activity.mCalled) {
3660 throw new SuperNotCalledException(
3661 "Activity " + activity.getLocalClassName() +
3662 " did not call through to super.onConfigurationChanged()");
3663 }
3664 activity.mConfigChangeFlags = 0;
3665 activity.mCurrentConfig = new Configuration(config);
3666 }
3667 }
3668 }
3669
3670 final void handleConfigurationChanged(Configuration config) {
Bob Leee5408332009-09-04 18:31:17 -07003671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 synchronized (mRelaunchingActivities) {
3673 if (mPendingConfiguration != null) {
3674 config = mPendingConfiguration;
3675 mPendingConfiguration = null;
3676 }
3677 }
Bob Leee5408332009-09-04 18:31:17 -07003678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 ArrayList<ComponentCallbacks> callbacks
3680 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 synchronized(mPackages) {
3683 if (mConfiguration == null) {
3684 mConfiguration = new Configuration();
3685 }
3686 mConfiguration.updateFrom(config);
3687 DisplayMetrics dm = getDisplayMetricsLocked(true);
3688
3689 // set it for java, this also affects newly created Resources
3690 if (config.locale != null) {
3691 Locale.setDefault(config.locale);
3692 }
3693
Dianne Hackborn0d907fa2009-07-27 20:48:50 -07003694 Resources.updateSystemConfiguration(config, dm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695
3696 ApplicationContext.ApplicationPackageManager.configurationChanged();
3697 //Log.i(TAG, "Configuration changed in " + currentPackageName());
3698 {
3699 Iterator<WeakReference<Resources>> it =
3700 mActiveResources.values().iterator();
3701 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3702 // mActiveResources.entrySet().iterator();
3703 while (it.hasNext()) {
3704 WeakReference<Resources> v = it.next();
3705 Resources r = v.get();
3706 if (r != null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003707 r.updateConfiguration(config, dm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 //Log.i(TAG, "Updated app resources " + v.getKey()
3709 // + " " + r + ": " + r.getConfiguration());
3710 } else {
3711 //Log.i(TAG, "Removing old resources " + v.getKey());
3712 it.remove();
3713 }
3714 }
3715 }
Bob Leee5408332009-09-04 18:31:17 -07003716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 callbacks = collectComponentCallbacksLocked(false, config);
3718 }
Bob Leee5408332009-09-04 18:31:17 -07003719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 final int N = callbacks.size();
3721 for (int i=0; i<N; i++) {
3722 performConfigurationChanged(callbacks.get(i), config);
3723 }
3724 }
3725
3726 final void handleActivityConfigurationChanged(IBinder token) {
3727 ActivityRecord r = mActivities.get(token);
3728 if (r == null || r.activity == null) {
3729 return;
3730 }
Bob Leee5408332009-09-04 18:31:17 -07003731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 performConfigurationChanged(r.activity, mConfiguration);
3733 }
3734
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003735 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003736 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003737 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003738 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3739 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003740 } catch (RuntimeException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003741 Log.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003742 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003743 } finally {
3744 try {
3745 pcd.fd.close();
3746 } catch (IOException e) {
3747 Log.w(TAG, "Failure closing profile fd", e);
3748 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003749 }
3750 } else {
3751 Debug.stopMethodTracing();
3752 }
3753 }
Bob Leee5408332009-09-04 18:31:17 -07003754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 final void handleLowMemory() {
3756 ArrayList<ComponentCallbacks> callbacks
3757 = new ArrayList<ComponentCallbacks>();
3758
3759 synchronized(mPackages) {
3760 callbacks = collectComponentCallbacksLocked(true, null);
3761 }
Bob Leee5408332009-09-04 18:31:17 -07003762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 final int N = callbacks.size();
3764 for (int i=0; i<N; i++) {
3765 callbacks.get(i).onLowMemory();
3766 }
3767
Chris Tatece229052009-03-25 16:44:52 -07003768 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3769 if (Process.myUid() != Process.SYSTEM_UID) {
3770 int sqliteReleased = SQLiteDatabase.releaseMemory();
3771 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3772 }
Bob Leee5408332009-09-04 18:31:17 -07003773
Mike Reedcaf0df12009-04-27 14:32:05 -04003774 // Ask graphics to free up as much as possible (font/image caches)
3775 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776
3777 BinderInternal.forceGc("mem");
3778 }
3779
3780 private final void handleBindApplication(AppBindData data) {
3781 mBoundApplication = data;
3782 mConfiguration = new Configuration(data.config);
3783
3784 // We now rely on this being set by zygote.
3785 //Process.setGid(data.appInfo.gid);
3786 //Process.setUid(data.appInfo.uid);
3787
3788 // send up app name; do this *before* waiting for debugger
3789 android.ddm.DdmHandleAppName.setAppName(data.processName);
3790
3791 /*
3792 * Before spawning a new process, reset the time zone to be the system time zone.
3793 * This needs to be done because the system time zone could have changed after the
3794 * the spawning of this process. Without doing this this process would have the incorrect
3795 * system time zone.
3796 */
3797 TimeZone.setDefault(null);
3798
3799 /*
3800 * Initialize the default locale in this process for the reasons we set the time zone.
3801 */
3802 Locale.setDefault(data.config.locale);
3803
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003804 /*
3805 * Update the system configuration since its preloaded and might not
3806 * reflect configuration changes. The configuration object passed
3807 * in AppBindData can be safely assumed to be up to date
3808 */
3809 Resources.getSystem().updateConfiguration(mConfiguration, null);
3810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 data.info = getPackageInfoNoCheck(data.appInfo);
3812
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003813 /**
3814 * Switch this process to density compatibility mode if needed.
3815 */
3816 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3817 == 0) {
3818 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3819 }
Bob Leee5408332009-09-04 18:31:17 -07003820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3822 // XXX should have option to change the port.
3823 Debug.changeDebugPort(8100);
3824 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
3825 Log.w(TAG, "Application " + data.info.getPackageName()
3826 + " is waiting for the debugger on port 8100...");
3827
3828 IActivityManager mgr = ActivityManagerNative.getDefault();
3829 try {
3830 mgr.showWaitingForDebugger(mAppThread, true);
3831 } catch (RemoteException ex) {
3832 }
3833
3834 Debug.waitForDebugger();
3835
3836 try {
3837 mgr.showWaitingForDebugger(mAppThread, false);
3838 } catch (RemoteException ex) {
3839 }
3840
3841 } else {
3842 Log.w(TAG, "Application " + data.info.getPackageName()
3843 + " can be debugged on port 8100...");
3844 }
3845 }
3846
3847 if (data.instrumentationName != null) {
3848 ApplicationContext appContext = new ApplicationContext();
3849 appContext.init(data.info, null, this);
3850 InstrumentationInfo ii = null;
3851 try {
3852 ii = appContext.getPackageManager().
3853 getInstrumentationInfo(data.instrumentationName, 0);
3854 } catch (PackageManager.NameNotFoundException e) {
3855 }
3856 if (ii == null) {
3857 throw new RuntimeException(
3858 "Unable to find instrumentation info for: "
3859 + data.instrumentationName);
3860 }
3861
3862 mInstrumentationAppDir = ii.sourceDir;
3863 mInstrumentationAppPackage = ii.packageName;
3864 mInstrumentedAppDir = data.info.getAppDir();
3865
3866 ApplicationInfo instrApp = new ApplicationInfo();
3867 instrApp.packageName = ii.packageName;
3868 instrApp.sourceDir = ii.sourceDir;
3869 instrApp.publicSourceDir = ii.publicSourceDir;
3870 instrApp.dataDir = ii.dataDir;
3871 PackageInfo pi = getPackageInfo(instrApp,
3872 appContext.getClassLoader(), false, true);
3873 ApplicationContext instrContext = new ApplicationContext();
3874 instrContext.init(pi, null, this);
3875
3876 try {
3877 java.lang.ClassLoader cl = instrContext.getClassLoader();
3878 mInstrumentation = (Instrumentation)
3879 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3880 } catch (Exception e) {
3881 throw new RuntimeException(
3882 "Unable to instantiate instrumentation "
3883 + data.instrumentationName + ": " + e.toString(), e);
3884 }
3885
3886 mInstrumentation.init(this, instrContext, appContext,
3887 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3888
3889 if (data.profileFile != null && !ii.handleProfiling) {
3890 data.handlingProfiling = true;
3891 File file = new File(data.profileFile);
3892 file.getParentFile().mkdirs();
3893 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3894 }
3895
3896 try {
3897 mInstrumentation.onCreate(data.instrumentationArgs);
3898 }
3899 catch (Exception e) {
3900 throw new RuntimeException(
3901 "Exception thrown in onCreate() of "
3902 + data.instrumentationName + ": " + e.toString(), e);
3903 }
3904
3905 } else {
3906 mInstrumentation = new Instrumentation();
3907 }
3908
Christopher Tate181fafa2009-05-14 11:12:14 -07003909 // If the app is being launched for full backup or restore, bring it up in
3910 // a restricted environment with the base application class.
3911 Application app = data.info.makeApplication(data.restrictedBackupMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 mInitialApplication = app;
3913
3914 List<ProviderInfo> providers = data.providers;
3915 if (providers != null) {
3916 installContentProviders(app, providers);
3917 }
3918
3919 try {
3920 mInstrumentation.callApplicationOnCreate(app);
3921 } catch (Exception e) {
3922 if (!mInstrumentation.onException(app, e)) {
3923 throw new RuntimeException(
3924 "Unable to create application " + app.getClass().getName()
3925 + ": " + e.toString(), e);
3926 }
3927 }
3928 }
3929
3930 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3931 IActivityManager am = ActivityManagerNative.getDefault();
3932 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3933 Debug.stopMethodTracing();
3934 }
3935 //Log.i(TAG, "am: " + ActivityManagerNative.getDefault()
3936 // + ", app thr: " + mAppThread);
3937 try {
3938 am.finishInstrumentation(mAppThread, resultCode, results);
3939 } catch (RemoteException ex) {
3940 }
3941 }
3942
3943 private final void installContentProviders(
3944 Context context, List<ProviderInfo> providers) {
3945 final ArrayList<IActivityManager.ContentProviderHolder> results =
3946 new ArrayList<IActivityManager.ContentProviderHolder>();
3947
3948 Iterator<ProviderInfo> i = providers.iterator();
3949 while (i.hasNext()) {
3950 ProviderInfo cpi = i.next();
3951 StringBuilder buf = new StringBuilder(128);
3952 buf.append("Publishing provider ");
3953 buf.append(cpi.authority);
3954 buf.append(": ");
3955 buf.append(cpi.name);
3956 Log.i(TAG, buf.toString());
3957 IContentProvider cp = installProvider(context, null, cpi, false);
3958 if (cp != null) {
3959 IActivityManager.ContentProviderHolder cph =
3960 new IActivityManager.ContentProviderHolder(cpi);
3961 cph.provider = cp;
3962 results.add(cph);
3963 // Don't ever unload this provider from the process.
3964 synchronized(mProviderMap) {
3965 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3966 }
3967 }
3968 }
3969
3970 try {
3971 ActivityManagerNative.getDefault().publishContentProviders(
3972 getApplicationThread(), results);
3973 } catch (RemoteException ex) {
3974 }
3975 }
3976
3977 private final IContentProvider getProvider(Context context, String name) {
3978 synchronized(mProviderMap) {
3979 final ProviderRecord pr = mProviderMap.get(name);
3980 if (pr != null) {
3981 return pr.mProvider;
3982 }
3983 }
3984
3985 IActivityManager.ContentProviderHolder holder = null;
3986 try {
3987 holder = ActivityManagerNative.getDefault().getContentProvider(
3988 getApplicationThread(), name);
3989 } catch (RemoteException ex) {
3990 }
3991 if (holder == null) {
3992 Log.e(TAG, "Failed to find provider info for " + name);
3993 return null;
3994 }
3995 if (holder.permissionFailure != null) {
3996 throw new SecurityException("Permission " + holder.permissionFailure
3997 + " required for provider " + name);
3998 }
3999
4000 IContentProvider prov = installProvider(context, holder.provider,
4001 holder.info, true);
4002 //Log.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
4003 if (holder.noReleaseNeeded || holder.provider == null) {
4004 // We are not going to release the provider if it is an external
4005 // provider that doesn't care about being released, or if it is
4006 // a local provider running in this process.
4007 //Log.i(TAG, "*** NO RELEASE NEEDED");
4008 synchronized(mProviderMap) {
4009 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
4010 }
4011 }
4012 return prov;
4013 }
4014
4015 public final IContentProvider acquireProvider(Context c, String name) {
4016 IContentProvider provider = getProvider(c, name);
4017 if(provider == null)
4018 return null;
4019 IBinder jBinder = provider.asBinder();
4020 synchronized(mProviderMap) {
4021 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4022 if(prc == null) {
4023 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4024 } else {
4025 prc.count++;
4026 } //end else
4027 } //end synchronized
4028 return provider;
4029 }
4030
4031 public final boolean releaseProvider(IContentProvider provider) {
4032 if(provider == null) {
4033 return false;
4034 }
4035 IBinder jBinder = provider.asBinder();
4036 synchronized(mProviderMap) {
4037 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4038 if(prc == null) {
4039 if(localLOGV) Log.v(TAG, "releaseProvider::Weird shouldnt be here");
4040 return false;
4041 } else {
4042 prc.count--;
4043 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004044 // Schedule the actual remove asynchronously, since we
4045 // don't know the context this will be called in.
4046 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4047 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 } //end if
4049 } //end else
4050 } //end synchronized
4051 return true;
4052 }
4053
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004054 final void completeRemoveProvider(IContentProvider provider) {
4055 IBinder jBinder = provider.asBinder();
4056 synchronized(mProviderMap) {
4057 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4058 if(prc != null && prc.count == 0) {
4059 mProviderRefCountMap.remove(jBinder);
4060 //invoke removeProvider to dereference provider
4061 removeProviderLocked(provider);
4062 }
4063 }
4064 }
4065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 public final void removeProviderLocked(IContentProvider provider) {
4067 if (provider == null) {
4068 return;
4069 }
4070 IBinder providerBinder = provider.asBinder();
4071 boolean amRemoveFlag = false;
4072
4073 // remove the provider from mProviderMap
4074 Iterator<ProviderRecord> iter = mProviderMap.values().iterator();
4075 while (iter.hasNext()) {
4076 ProviderRecord pr = iter.next();
4077 IBinder myBinder = pr.mProvider.asBinder();
4078 if (myBinder == providerBinder) {
4079 //find if its published by this process itself
4080 if(pr.mLocalProvider != null) {
4081 if(localLOGV) Log.i(TAG, "removeProvider::found local provider returning");
4082 return;
4083 }
4084 if(localLOGV) Log.v(TAG, "removeProvider::Not local provider Unlinking " +
4085 "death recipient");
4086 //content provider is in another process
4087 myBinder.unlinkToDeath(pr, 0);
4088 iter.remove();
4089 //invoke remove only once for the very first name seen
4090 if(!amRemoveFlag) {
4091 try {
4092 if(localLOGV) Log.v(TAG, "removeProvider::Invoking " +
4093 "ActivityManagerNative.removeContentProvider("+pr.mName);
4094 ActivityManagerNative.getDefault().removeContentProvider(getApplicationThread(), pr.mName);
4095 amRemoveFlag = true;
4096 } catch (RemoteException e) {
4097 //do nothing content provider object is dead any way
4098 } //end catch
4099 }
4100 } //end if myBinder
4101 } //end while iter
4102 }
4103
4104 final void removeDeadProvider(String name, IContentProvider provider) {
4105 synchronized(mProviderMap) {
4106 ProviderRecord pr = mProviderMap.get(name);
4107 if (pr.mProvider.asBinder() == provider.asBinder()) {
4108 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004109 ProviderRecord removed = mProviderMap.remove(name);
4110 if (removed != null) {
4111 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 }
4114 }
4115 }
4116
4117 final void removeDeadProviderLocked(String name, IContentProvider provider) {
4118 ProviderRecord pr = mProviderMap.get(name);
4119 if (pr.mProvider.asBinder() == provider.asBinder()) {
4120 Log.i(TAG, "Removing dead content provider: " + name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004121 ProviderRecord removed = mProviderMap.remove(name);
4122 if (removed != null) {
4123 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 }
4126 }
4127
4128 private final IContentProvider installProvider(Context context,
4129 IContentProvider provider, ProviderInfo info, boolean noisy) {
4130 ContentProvider localProvider = null;
4131 if (provider == null) {
4132 if (noisy) {
4133 Log.d(TAG, "Loading provider " + info.authority + ": "
4134 + info.name);
4135 }
4136 Context c = null;
4137 ApplicationInfo ai = info.applicationInfo;
4138 if (context.getPackageName().equals(ai.packageName)) {
4139 c = context;
4140 } else if (mInitialApplication != null &&
4141 mInitialApplication.getPackageName().equals(ai.packageName)) {
4142 c = mInitialApplication;
4143 } else {
4144 try {
4145 c = context.createPackageContext(ai.packageName,
4146 Context.CONTEXT_INCLUDE_CODE);
4147 } catch (PackageManager.NameNotFoundException e) {
4148 }
4149 }
4150 if (c == null) {
4151 Log.w(TAG, "Unable to get context for package " +
4152 ai.packageName +
4153 " while loading content provider " +
4154 info.name);
4155 return null;
4156 }
4157 try {
4158 final java.lang.ClassLoader cl = c.getClassLoader();
4159 localProvider = (ContentProvider)cl.
4160 loadClass(info.name).newInstance();
4161 provider = localProvider.getIContentProvider();
4162 if (provider == null) {
4163 Log.e(TAG, "Failed to instantiate class " +
4164 info.name + " from sourceDir " +
4165 info.applicationInfo.sourceDir);
4166 return null;
4167 }
4168 if (Config.LOGV) Log.v(
4169 TAG, "Instantiating local provider " + info.name);
4170 // XXX Need to create the correct context for this provider.
4171 localProvider.attachInfo(c, info);
4172 } catch (java.lang.Exception e) {
4173 if (!mInstrumentation.onException(null, e)) {
4174 throw new RuntimeException(
4175 "Unable to get provider " + info.name
4176 + ": " + e.toString(), e);
4177 }
4178 return null;
4179 }
4180 } else if (localLOGV) {
4181 Log.v(TAG, "Installing external provider " + info.authority + ": "
4182 + info.name);
4183 }
4184
4185 synchronized (mProviderMap) {
4186 // Cache the pointer for the remote provider.
4187 String names[] = PATTERN_SEMICOLON.split(info.authority);
4188 for (int i=0; i<names.length; i++) {
4189 ProviderRecord pr = new ProviderRecord(names[i], provider,
4190 localProvider);
4191 try {
4192 provider.asBinder().linkToDeath(pr, 0);
4193 mProviderMap.put(names[i], pr);
4194 } catch (RemoteException e) {
4195 return null;
4196 }
4197 }
4198 if (localProvider != null) {
4199 mLocalProviders.put(provider.asBinder(),
4200 new ProviderRecord(null, provider, localProvider));
4201 }
4202 }
4203
4204 return provider;
4205 }
4206
4207 private final void attach(boolean system) {
4208 sThreadLocal.set(this);
4209 mSystemThread = system;
4210 AndroidHttpClient.setThreadBlocked(true);
4211 if (!system) {
4212 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4213 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4214 IActivityManager mgr = ActivityManagerNative.getDefault();
4215 try {
4216 mgr.attachApplication(mAppThread);
4217 } catch (RemoteException ex) {
4218 }
4219 } else {
4220 // Don't set application object here -- if the system crashes,
4221 // we can't display an alert, we just want to die die die.
4222 android.ddm.DdmHandleAppName.setAppName("system_process");
4223 try {
4224 mInstrumentation = new Instrumentation();
4225 ApplicationContext context = new ApplicationContext();
4226 context.init(getSystemContext().mPackageInfo, null, this);
4227 Application app = Instrumentation.newApplication(Application.class, context);
4228 mAllApplications.add(app);
4229 mInitialApplication = app;
4230 app.onCreate();
4231 } catch (Exception e) {
4232 throw new RuntimeException(
4233 "Unable to instantiate Application():" + e.toString(), e);
4234 }
4235 }
4236 }
4237
4238 private final void detach()
4239 {
4240 AndroidHttpClient.setThreadBlocked(false);
4241 sThreadLocal.set(null);
4242 }
4243
4244 public static final ActivityThread systemMain() {
4245 ActivityThread thread = new ActivityThread();
4246 thread.attach(true);
4247 return thread;
4248 }
4249
4250 public final void installSystemProviders(List providers) {
4251 if (providers != null) {
4252 installContentProviders(mInitialApplication,
4253 (List<ProviderInfo>)providers);
4254 }
4255 }
4256
4257 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004258 SamplingProfilerIntegration.start();
4259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 Process.setArgV0("<pre-initialized>");
4261
4262 Looper.prepareMainLooper();
4263
4264 ActivityThread thread = new ActivityThread();
4265 thread.attach(false);
4266
4267 Looper.loop();
4268
4269 if (Process.supportsProcesses()) {
4270 throw new RuntimeException("Main thread loop unexpectedly exited");
4271 }
4272
4273 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02004274 String name = (thread.mInitialApplication != null)
4275 ? thread.mInitialApplication.getPackageName()
4276 : "<unknown>";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 Log.i(TAG, "Main thread of " + name + " is now exiting");
4278 }
4279}