ActivityThread.java revision 399cccb85749e02f6d3e12d1d2846310e7cbfdf1
1/* 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.app.backup.BackupAgent; 20import android.content.BroadcastReceiver; 21import android.content.ComponentCallbacks; 22import android.content.ComponentName; 23import android.content.ContentProvider; 24import android.content.Context; 25import android.content.IContentProvider; 26import android.content.Intent; 27import android.content.IIntentReceiver; 28import android.content.ServiceConnection; 29import android.content.pm.ActivityInfo; 30import android.content.pm.ApplicationInfo; 31import android.content.pm.IPackageManager; 32import android.content.pm.InstrumentationInfo; 33import android.content.pm.PackageManager; 34import android.content.pm.ProviderInfo; 35import android.content.pm.ServiceInfo; 36import android.content.res.AssetManager; 37import android.content.res.CompatibilityInfo; 38import android.content.res.Configuration; 39import android.content.res.Resources; 40import android.database.sqlite.SQLiteDatabase; 41import android.database.sqlite.SQLiteDebug; 42import android.database.sqlite.SQLiteDebug.DbStats; 43import android.graphics.Bitmap; 44import android.graphics.Canvas; 45import android.os.Bundle; 46import android.os.Debug; 47import android.os.Handler; 48import android.os.IBinder; 49import android.os.Looper; 50import android.os.Message; 51import android.os.MessageQueue; 52import android.os.ParcelFileDescriptor; 53import android.os.Process; 54import android.os.RemoteException; 55import android.os.ServiceManager; 56import android.os.SystemClock; 57import android.util.AndroidRuntimeException; 58import android.util.Config; 59import android.util.DisplayMetrics; 60import android.util.EventLog; 61import android.util.Log; 62import android.util.Slog; 63import android.view.Display; 64import android.view.View; 65import android.view.ViewDebug; 66import android.view.ViewManager; 67import android.view.ViewRoot; 68import android.view.Window; 69import android.view.WindowManager; 70import android.view.WindowManagerImpl; 71 72import com.android.internal.os.BinderInternal; 73import com.android.internal.os.RuntimeInit; 74import com.android.internal.os.SamplingProfilerIntegration; 75import com.android.internal.util.ArrayUtils; 76 77import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl; 78 79import java.io.File; 80import java.io.FileDescriptor; 81import java.io.FileOutputStream; 82import java.io.IOException; 83import java.io.InputStream; 84import java.io.PrintWriter; 85import java.lang.ref.WeakReference; 86import java.net.URL; 87import java.util.ArrayList; 88import java.util.Enumeration; 89import java.util.HashMap; 90import java.util.Iterator; 91import java.util.List; 92import java.util.Locale; 93import java.util.Map; 94import java.util.TimeZone; 95import java.util.regex.Pattern; 96 97import dalvik.system.SamplingProfiler; 98 99final class IntentReceiverLeaked extends AndroidRuntimeException { 100 public IntentReceiverLeaked(String msg) { 101 super(msg); 102 } 103} 104 105final class ServiceConnectionLeaked extends AndroidRuntimeException { 106 public ServiceConnectionLeaked(String msg) { 107 super(msg); 108 } 109} 110 111final class SuperNotCalledException extends AndroidRuntimeException { 112 public SuperNotCalledException(String msg) { 113 super(msg); 114 } 115} 116 117/** 118 * This manages the execution of the main thread in an 119 * application process, scheduling and executing activities, 120 * broadcasts, and other operations on it as the activity 121 * manager requests. 122 * 123 * {@hide} 124 */ 125public final class ActivityThread { 126 private static final String TAG = "ActivityThread"; 127 private static final boolean DEBUG = false; 128 private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV; 129 private static final boolean DEBUG_BROADCAST = false; 130 private static final boolean DEBUG_RESULTS = false; 131 private static final boolean DEBUG_BACKUP = false; 132 private static final boolean DEBUG_CONFIGURATION = false; 133 private static final long MIN_TIME_BETWEEN_GCS = 5*1000; 134 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";"); 135 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003; 136 private static final int LOG_ON_PAUSE_CALLED = 30021; 137 private static final int LOG_ON_RESUME_CALLED = 30022; 138 139 140 public static final ActivityThread currentActivityThread() { 141 return (ActivityThread)sThreadLocal.get(); 142 } 143 144 public static final String currentPackageName() 145 { 146 ActivityThread am = currentActivityThread(); 147 return (am != null && am.mBoundApplication != null) 148 ? am.mBoundApplication.processName : null; 149 } 150 151 public static IPackageManager getPackageManager() { 152 if (sPackageManager != null) { 153 //Slog.v("PackageManager", "returning cur default = " + sPackageManager); 154 return sPackageManager; 155 } 156 IBinder b = ServiceManager.getService("package"); 157 //Slog.v("PackageManager", "default service binder = " + b); 158 sPackageManager = IPackageManager.Stub.asInterface(b); 159 //Slog.v("PackageManager", "default service = " + sPackageManager); 160 return sPackageManager; 161 } 162 163 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) { 164 if (mDisplayMetrics != null && !forceUpdate) { 165 return mDisplayMetrics; 166 } 167 if (mDisplay == null) { 168 WindowManager wm = WindowManagerImpl.getDefault(); 169 mDisplay = wm.getDefaultDisplay(); 170 } 171 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics(); 172 mDisplay.getMetrics(metrics); 173 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h=" 174 // + metrics.heightPixels + " den=" + metrics.density 175 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi); 176 return metrics; 177 } 178 179 /** 180 * Creates the top level Resources for applications with the given compatibility info. 181 * 182 * @param resDir the resource directory. 183 * @param compInfo the compability info. It will use the default compatibility info when it's 184 * null. 185 */ 186 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) { 187 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale); 188 Resources r; 189 synchronized (mPackages) { 190 // Resources is app scale dependent. 191 if (false) { 192 Slog.w(TAG, "getTopLevelResources: " + resDir + " / " 193 + compInfo.applicationScale); 194 } 195 WeakReference<Resources> wr = mActiveResources.get(key); 196 r = wr != null ? wr.get() : null; 197 if (r != null && r.getAssets().isUpToDate()) { 198 if (false) { 199 Slog.w(TAG, "Returning cached resources " + r + " " + resDir 200 + ": appScale=" + r.getCompatibilityInfo().applicationScale); 201 } 202 return r; 203 } 204 } 205 206 //if (r != null) { 207 // Slog.w(TAG, "Throwing away out-of-date resources!!!! " 208 // + r + " " + resDir); 209 //} 210 211 AssetManager assets = new AssetManager(); 212 if (assets.addAssetPath(resDir) == 0) { 213 return null; 214 } 215 216 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics); 217 DisplayMetrics metrics = getDisplayMetricsLocked(false); 218 r = new Resources(assets, metrics, getConfiguration(), compInfo); 219 if (false) { 220 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": " 221 + r.getConfiguration() + " appScale=" 222 + r.getCompatibilityInfo().applicationScale); 223 } 224 225 synchronized (mPackages) { 226 WeakReference<Resources> wr = mActiveResources.get(key); 227 Resources existing = wr != null ? wr.get() : null; 228 if (existing != null && existing.getAssets().isUpToDate()) { 229 // Someone else already created the resources while we were 230 // unlocked; go ahead and use theirs. 231 r.getAssets().close(); 232 return existing; 233 } 234 235 // XXX need to remove entries when weak references go away 236 mActiveResources.put(key, new WeakReference<Resources>(r)); 237 return r; 238 } 239 } 240 241 /** 242 * Creates the top level resources for the given package. 243 */ 244 Resources getTopLevelResources(String resDir, PackageInfo pkgInfo) { 245 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo); 246 } 247 248 final Handler getHandler() { 249 return mH; 250 } 251 252 public final static class PackageInfo { 253 254 private final ActivityThread mActivityThread; 255 private final ApplicationInfo mApplicationInfo; 256 private final String mPackageName; 257 private final String mAppDir; 258 private final String mResDir; 259 private final String[] mSharedLibraries; 260 private final String mDataDir; 261 private final File mDataDirFile; 262 private final ClassLoader mBaseClassLoader; 263 private final boolean mSecurityViolation; 264 private final boolean mIncludeCode; 265 private Resources mResources; 266 private ClassLoader mClassLoader; 267 private Application mApplication; 268 private CompatibilityInfo mCompatibilityInfo; 269 270 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mReceivers 271 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>(); 272 private final HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>> mUnregisteredReceivers 273 = new HashMap<Context, HashMap<BroadcastReceiver, ReceiverDispatcher>>(); 274 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mServices 275 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>(); 276 private final HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>> mUnboundServices 277 = new HashMap<Context, HashMap<ServiceConnection, ServiceDispatcher>>(); 278 279 int mClientCount = 0; 280 281 Application getApplication() { 282 return mApplication; 283 } 284 285 public PackageInfo(ActivityThread activityThread, ApplicationInfo aInfo, 286 ActivityThread mainThread, ClassLoader baseLoader, 287 boolean securityViolation, boolean includeCode) { 288 mActivityThread = activityThread; 289 mApplicationInfo = aInfo; 290 mPackageName = aInfo.packageName; 291 mAppDir = aInfo.sourceDir; 292 mResDir = aInfo.uid == Process.myUid() ? aInfo.sourceDir 293 : aInfo.publicSourceDir; 294 mSharedLibraries = aInfo.sharedLibraryFiles; 295 mDataDir = aInfo.dataDir; 296 mDataDirFile = mDataDir != null ? new File(mDataDir) : null; 297 mBaseClassLoader = baseLoader; 298 mSecurityViolation = securityViolation; 299 mIncludeCode = includeCode; 300 mCompatibilityInfo = new CompatibilityInfo(aInfo); 301 302 if (mAppDir == null) { 303 if (mSystemContext == null) { 304 mSystemContext = 305 ContextImpl.createSystemContext(mainThread); 306 mSystemContext.getResources().updateConfiguration( 307 mainThread.getConfiguration(), 308 mainThread.getDisplayMetricsLocked(false)); 309 //Slog.i(TAG, "Created system resources " 310 // + mSystemContext.getResources() + ": " 311 // + mSystemContext.getResources().getConfiguration()); 312 } 313 mClassLoader = mSystemContext.getClassLoader(); 314 mResources = mSystemContext.getResources(); 315 } 316 } 317 318 public PackageInfo(ActivityThread activityThread, String name, 319 Context systemContext, ApplicationInfo info) { 320 mActivityThread = activityThread; 321 mApplicationInfo = info != null ? info : new ApplicationInfo(); 322 mApplicationInfo.packageName = name; 323 mPackageName = name; 324 mAppDir = null; 325 mResDir = null; 326 mSharedLibraries = null; 327 mDataDir = null; 328 mDataDirFile = null; 329 mBaseClassLoader = null; 330 mSecurityViolation = false; 331 mIncludeCode = true; 332 mClassLoader = systemContext.getClassLoader(); 333 mResources = systemContext.getResources(); 334 mCompatibilityInfo = new CompatibilityInfo(mApplicationInfo); 335 } 336 337 public String getPackageName() { 338 return mPackageName; 339 } 340 341 public ApplicationInfo getApplicationInfo() { 342 return mApplicationInfo; 343 } 344 345 public boolean isSecurityViolation() { 346 return mSecurityViolation; 347 } 348 349 /** 350 * Gets the array of shared libraries that are listed as 351 * used by the given package. 352 * 353 * @param packageName the name of the package (note: not its 354 * file name) 355 * @return null-ok; the array of shared libraries, each one 356 * a fully-qualified path 357 */ 358 private static String[] getLibrariesFor(String packageName) { 359 ApplicationInfo ai = null; 360 try { 361 ai = getPackageManager().getApplicationInfo(packageName, 362 PackageManager.GET_SHARED_LIBRARY_FILES); 363 } catch (RemoteException e) { 364 throw new AssertionError(e); 365 } 366 367 if (ai == null) { 368 return null; 369 } 370 371 return ai.sharedLibraryFiles; 372 } 373 374 /** 375 * Combines two arrays (of library names) such that they are 376 * concatenated in order but are devoid of duplicates. The 377 * result is a single string with the names of the libraries 378 * separated by colons, or <code>null</code> if both lists 379 * were <code>null</code> or empty. 380 * 381 * @param list1 null-ok; the first list 382 * @param list2 null-ok; the second list 383 * @return null-ok; the combination 384 */ 385 private static String combineLibs(String[] list1, String[] list2) { 386 StringBuilder result = new StringBuilder(300); 387 boolean first = true; 388 389 if (list1 != null) { 390 for (String s : list1) { 391 if (first) { 392 first = false; 393 } else { 394 result.append(':'); 395 } 396 result.append(s); 397 } 398 } 399 400 // Only need to check for duplicates if list1 was non-empty. 401 boolean dupCheck = !first; 402 403 if (list2 != null) { 404 for (String s : list2) { 405 if (dupCheck && ArrayUtils.contains(list1, s)) { 406 continue; 407 } 408 409 if (first) { 410 first = false; 411 } else { 412 result.append(':'); 413 } 414 result.append(s); 415 } 416 } 417 418 return result.toString(); 419 } 420 421 public ClassLoader getClassLoader() { 422 synchronized (this) { 423 if (mClassLoader != null) { 424 return mClassLoader; 425 } 426 427 if (mIncludeCode && !mPackageName.equals("android")) { 428 String zip = mAppDir; 429 430 /* 431 * The following is a bit of a hack to inject 432 * instrumentation into the system: If the app 433 * being started matches one of the instrumentation names, 434 * then we combine both the "instrumentation" and 435 * "instrumented" app into the path, along with the 436 * concatenation of both apps' shared library lists. 437 */ 438 439 String instrumentationAppDir = 440 mActivityThread.mInstrumentationAppDir; 441 String instrumentationAppPackage = 442 mActivityThread.mInstrumentationAppPackage; 443 String instrumentedAppDir = 444 mActivityThread.mInstrumentedAppDir; 445 String[] instrumentationLibs = null; 446 447 if (mAppDir.equals(instrumentationAppDir) 448 || mAppDir.equals(instrumentedAppDir)) { 449 zip = instrumentationAppDir + ":" + instrumentedAppDir; 450 if (! instrumentedAppDir.equals(instrumentationAppDir)) { 451 instrumentationLibs = 452 getLibrariesFor(instrumentationAppPackage); 453 } 454 } 455 456 if ((mSharedLibraries != null) || 457 (instrumentationLibs != null)) { 458 zip = 459 combineLibs(mSharedLibraries, instrumentationLibs) 460 + ':' + zip; 461 } 462 463 /* 464 * With all the combination done (if necessary, actually 465 * create the class loader. 466 */ 467 468 if (localLOGV) Slog.v(TAG, "Class path: " + zip); 469 470 mClassLoader = 471 ApplicationLoaders.getDefault().getClassLoader( 472 zip, mDataDir, mBaseClassLoader); 473 initializeJavaContextClassLoader(); 474 } else { 475 if (mBaseClassLoader == null) { 476 mClassLoader = ClassLoader.getSystemClassLoader(); 477 } else { 478 mClassLoader = mBaseClassLoader; 479 } 480 } 481 return mClassLoader; 482 } 483 } 484 485 /** 486 * Setup value for Thread.getContextClassLoader(). If the 487 * package will not run in in a VM with other packages, we set 488 * the Java context ClassLoader to the 489 * PackageInfo.getClassLoader value. However, if this VM can 490 * contain multiple packages, we intead set the Java context 491 * ClassLoader to a proxy that will warn about the use of Java 492 * context ClassLoaders and then fall through to use the 493 * system ClassLoader. 494 * 495 * <p> Note that this is similar to but not the same as the 496 * android.content.Context.getClassLoader(). While both 497 * context class loaders are typically set to the 498 * PathClassLoader used to load the package archive in the 499 * single application per VM case, a single Android process 500 * may contain several Contexts executing on one thread with 501 * their own logical ClassLoaders while the Java context 502 * ClassLoader is a thread local. This is why in the case when 503 * we have multiple packages per VM we do not set the Java 504 * context ClassLoader to an arbitrary but instead warn the 505 * user to set their own if we detect that they are using a 506 * Java library that expects it to be set. 507 */ 508 private void initializeJavaContextClassLoader() { 509 IPackageManager pm = getPackageManager(); 510 android.content.pm.PackageInfo pi; 511 try { 512 pi = pm.getPackageInfo(mPackageName, 0); 513 } catch (RemoteException e) { 514 throw new AssertionError(e); 515 } 516 /* 517 * Two possible indications that this package could be 518 * sharing its virtual machine with other packages: 519 * 520 * 1.) the sharedUserId attribute is set in the manifest, 521 * indicating a request to share a VM with other 522 * packages with the same sharedUserId. 523 * 524 * 2.) the application element of the manifest has an 525 * attribute specifying a non-default process name, 526 * indicating the desire to run in another packages VM. 527 */ 528 boolean sharedUserIdSet = (pi.sharedUserId != null); 529 boolean processNameNotDefault = 530 (pi.applicationInfo != null && 531 !mPackageName.equals(pi.applicationInfo.processName)); 532 boolean sharable = (sharedUserIdSet || processNameNotDefault); 533 ClassLoader contextClassLoader = 534 (sharable) 535 ? new WarningContextClassLoader() 536 : mClassLoader; 537 Thread.currentThread().setContextClassLoader(contextClassLoader); 538 } 539 540 private static class WarningContextClassLoader extends ClassLoader { 541 542 private static boolean warned = false; 543 544 private void warn(String methodName) { 545 if (warned) { 546 return; 547 } 548 warned = true; 549 Thread.currentThread().setContextClassLoader(getParent()); 550 Slog.w(TAG, "ClassLoader." + methodName + ": " + 551 "The class loader returned by " + 552 "Thread.getContextClassLoader() may fail for processes " + 553 "that host multiple applications. You should explicitly " + 554 "specify a context class loader. For example: " + 555 "Thread.setContextClassLoader(getClass().getClassLoader());"); 556 } 557 558 @Override public URL getResource(String resName) { 559 warn("getResource"); 560 return getParent().getResource(resName); 561 } 562 563 @Override public Enumeration<URL> getResources(String resName) throws IOException { 564 warn("getResources"); 565 return getParent().getResources(resName); 566 } 567 568 @Override public InputStream getResourceAsStream(String resName) { 569 warn("getResourceAsStream"); 570 return getParent().getResourceAsStream(resName); 571 } 572 573 @Override public Class<?> loadClass(String className) throws ClassNotFoundException { 574 warn("loadClass"); 575 return getParent().loadClass(className); 576 } 577 578 @Override public void setClassAssertionStatus(String cname, boolean enable) { 579 warn("setClassAssertionStatus"); 580 getParent().setClassAssertionStatus(cname, enable); 581 } 582 583 @Override public void setPackageAssertionStatus(String pname, boolean enable) { 584 warn("setPackageAssertionStatus"); 585 getParent().setPackageAssertionStatus(pname, enable); 586 } 587 588 @Override public void setDefaultAssertionStatus(boolean enable) { 589 warn("setDefaultAssertionStatus"); 590 getParent().setDefaultAssertionStatus(enable); 591 } 592 593 @Override public void clearAssertionStatus() { 594 warn("clearAssertionStatus"); 595 getParent().clearAssertionStatus(); 596 } 597 } 598 599 public String getAppDir() { 600 return mAppDir; 601 } 602 603 public String getResDir() { 604 return mResDir; 605 } 606 607 public String getDataDir() { 608 return mDataDir; 609 } 610 611 public File getDataDirFile() { 612 return mDataDirFile; 613 } 614 615 public AssetManager getAssets(ActivityThread mainThread) { 616 return getResources(mainThread).getAssets(); 617 } 618 619 public Resources getResources(ActivityThread mainThread) { 620 if (mResources == null) { 621 mResources = mainThread.getTopLevelResources(mResDir, this); 622 } 623 return mResources; 624 } 625 626 public Application makeApplication(boolean forceDefaultAppClass, 627 Instrumentation instrumentation) { 628 if (mApplication != null) { 629 return mApplication; 630 } 631 632 Application app = null; 633 634 String appClass = mApplicationInfo.className; 635 if (forceDefaultAppClass || (appClass == null)) { 636 appClass = "android.app.Application"; 637 } 638 639 try { 640 java.lang.ClassLoader cl = getClassLoader(); 641 ContextImpl appContext = new ContextImpl(); 642 appContext.init(this, null, mActivityThread); 643 app = mActivityThread.mInstrumentation.newApplication( 644 cl, appClass, appContext); 645 appContext.setOuterContext(app); 646 } catch (Exception e) { 647 if (!mActivityThread.mInstrumentation.onException(app, e)) { 648 throw new RuntimeException( 649 "Unable to instantiate application " + appClass 650 + ": " + e.toString(), e); 651 } 652 } 653 mActivityThread.mAllApplications.add(app); 654 mApplication = app; 655 656 if (instrumentation != null) { 657 try { 658 instrumentation.callApplicationOnCreate(app); 659 } catch (Exception e) { 660 if (!instrumentation.onException(app, e)) { 661 throw new RuntimeException( 662 "Unable to create application " + app.getClass().getName() 663 + ": " + e.toString(), e); 664 } 665 } 666 } 667 668 return app; 669 } 670 671 public void removeContextRegistrations(Context context, 672 String who, String what) { 673 HashMap<BroadcastReceiver, ReceiverDispatcher> rmap = 674 mReceivers.remove(context); 675 if (rmap != null) { 676 Iterator<ReceiverDispatcher> it = rmap.values().iterator(); 677 while (it.hasNext()) { 678 ReceiverDispatcher rd = it.next(); 679 IntentReceiverLeaked leak = new IntentReceiverLeaked( 680 what + " " + who + " has leaked IntentReceiver " 681 + rd.getIntentReceiver() + " that was " + 682 "originally registered here. Are you missing a " + 683 "call to unregisterReceiver()?"); 684 leak.setStackTrace(rd.getLocation().getStackTrace()); 685 Slog.e(TAG, leak.getMessage(), leak); 686 try { 687 ActivityManagerNative.getDefault().unregisterReceiver( 688 rd.getIIntentReceiver()); 689 } catch (RemoteException e) { 690 // system crashed, nothing we can do 691 } 692 } 693 } 694 mUnregisteredReceivers.remove(context); 695 //Slog.i(TAG, "Receiver registrations: " + mReceivers); 696 HashMap<ServiceConnection, ServiceDispatcher> smap = 697 mServices.remove(context); 698 if (smap != null) { 699 Iterator<ServiceDispatcher> it = smap.values().iterator(); 700 while (it.hasNext()) { 701 ServiceDispatcher sd = it.next(); 702 ServiceConnectionLeaked leak = new ServiceConnectionLeaked( 703 what + " " + who + " has leaked ServiceConnection " 704 + sd.getServiceConnection() + " that was originally bound here"); 705 leak.setStackTrace(sd.getLocation().getStackTrace()); 706 Slog.e(TAG, leak.getMessage(), leak); 707 try { 708 ActivityManagerNative.getDefault().unbindService( 709 sd.getIServiceConnection()); 710 } catch (RemoteException e) { 711 // system crashed, nothing we can do 712 } 713 sd.doForget(); 714 } 715 } 716 mUnboundServices.remove(context); 717 //Slog.i(TAG, "Service registrations: " + mServices); 718 } 719 720 public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r, 721 Context context, Handler handler, 722 Instrumentation instrumentation, boolean registered) { 723 synchronized (mReceivers) { 724 ReceiverDispatcher rd = null; 725 HashMap<BroadcastReceiver, ReceiverDispatcher> map = null; 726 if (registered) { 727 map = mReceivers.get(context); 728 if (map != null) { 729 rd = map.get(r); 730 } 731 } 732 if (rd == null) { 733 rd = new ReceiverDispatcher(r, context, handler, 734 instrumentation, registered); 735 if (registered) { 736 if (map == null) { 737 map = new HashMap<BroadcastReceiver, ReceiverDispatcher>(); 738 mReceivers.put(context, map); 739 } 740 map.put(r, rd); 741 } 742 } else { 743 rd.validate(context, handler); 744 } 745 return rd.getIIntentReceiver(); 746 } 747 } 748 749 public IIntentReceiver forgetReceiverDispatcher(Context context, 750 BroadcastReceiver r) { 751 synchronized (mReceivers) { 752 HashMap<BroadcastReceiver, ReceiverDispatcher> map = mReceivers.get(context); 753 ReceiverDispatcher rd = null; 754 if (map != null) { 755 rd = map.get(r); 756 if (rd != null) { 757 map.remove(r); 758 if (map.size() == 0) { 759 mReceivers.remove(context); 760 } 761 if (r.getDebugUnregister()) { 762 HashMap<BroadcastReceiver, ReceiverDispatcher> holder 763 = mUnregisteredReceivers.get(context); 764 if (holder == null) { 765 holder = new HashMap<BroadcastReceiver, ReceiverDispatcher>(); 766 mUnregisteredReceivers.put(context, holder); 767 } 768 RuntimeException ex = new IllegalArgumentException( 769 "Originally unregistered here:"); 770 ex.fillInStackTrace(); 771 rd.setUnregisterLocation(ex); 772 holder.put(r, rd); 773 } 774 return rd.getIIntentReceiver(); 775 } 776 } 777 HashMap<BroadcastReceiver, ReceiverDispatcher> holder 778 = mUnregisteredReceivers.get(context); 779 if (holder != null) { 780 rd = holder.get(r); 781 if (rd != null) { 782 RuntimeException ex = rd.getUnregisterLocation(); 783 throw new IllegalArgumentException( 784 "Unregistering Receiver " + r 785 + " that was already unregistered", ex); 786 } 787 } 788 if (context == null) { 789 throw new IllegalStateException("Unbinding Receiver " + r 790 + " from Context that is no longer in use: " + context); 791 } else { 792 throw new IllegalArgumentException("Receiver not registered: " + r); 793 } 794 795 } 796 } 797 798 static final class ReceiverDispatcher { 799 800 final static class InnerReceiver extends IIntentReceiver.Stub { 801 final WeakReference<ReceiverDispatcher> mDispatcher; 802 final ReceiverDispatcher mStrongRef; 803 804 InnerReceiver(ReceiverDispatcher rd, boolean strong) { 805 mDispatcher = new WeakReference<ReceiverDispatcher>(rd); 806 mStrongRef = strong ? rd : null; 807 } 808 public void performReceive(Intent intent, int resultCode, 809 String data, Bundle extras, boolean ordered, boolean sticky) { 810 ReceiverDispatcher rd = mDispatcher.get(); 811 if (DEBUG_BROADCAST) { 812 int seq = intent.getIntExtra("seq", -1); 813 Slog.i(TAG, "Receiving broadcast " + intent.getAction() + " seq=" + seq 814 + " to " + (rd != null ? rd.mReceiver : null)); 815 } 816 if (rd != null) { 817 rd.performReceive(intent, resultCode, data, extras, 818 ordered, sticky); 819 } else { 820 // The activity manager dispatched a broadcast to a registered 821 // receiver in this process, but before it could be delivered the 822 // receiver was unregistered. Acknowledge the broadcast on its 823 // behalf so that the system's broadcast sequence can continue. 824 if (DEBUG_BROADCAST) Slog.i(TAG, 825 "Finishing broadcast to unregistered receiver"); 826 IActivityManager mgr = ActivityManagerNative.getDefault(); 827 try { 828 mgr.finishReceiver(this, resultCode, data, extras, false); 829 } catch (RemoteException e) { 830 Slog.w(TAG, "Couldn't finish broadcast to unregistered receiver"); 831 } 832 } 833 } 834 } 835 836 final IIntentReceiver.Stub mIIntentReceiver; 837 final BroadcastReceiver mReceiver; 838 final Context mContext; 839 final Handler mActivityThread; 840 final Instrumentation mInstrumentation; 841 final boolean mRegistered; 842 final IntentReceiverLeaked mLocation; 843 RuntimeException mUnregisterLocation; 844 845 final class Args implements Runnable { 846 private Intent mCurIntent; 847 private int mCurCode; 848 private String mCurData; 849 private Bundle mCurMap; 850 private boolean mCurOrdered; 851 private boolean mCurSticky; 852 853 public void run() { 854 BroadcastReceiver receiver = mReceiver; 855 if (DEBUG_BROADCAST) { 856 int seq = mCurIntent.getIntExtra("seq", -1); 857 Slog.i(TAG, "Dispatching broadcast " + mCurIntent.getAction() 858 + " seq=" + seq + " to " + mReceiver); 859 Slog.i(TAG, " mRegistered=" + mRegistered 860 + " mCurOrdered=" + mCurOrdered); 861 } 862 863 IActivityManager mgr = ActivityManagerNative.getDefault(); 864 Intent intent = mCurIntent; 865 mCurIntent = null; 866 867 if (receiver == null) { 868 if (mRegistered && mCurOrdered) { 869 try { 870 if (DEBUG_BROADCAST) Slog.i(TAG, 871 "Finishing null broadcast to " + mReceiver); 872 mgr.finishReceiver(mIIntentReceiver, 873 mCurCode, mCurData, mCurMap, false); 874 } catch (RemoteException ex) { 875 } 876 } 877 return; 878 } 879 880 try { 881 ClassLoader cl = mReceiver.getClass().getClassLoader(); 882 intent.setExtrasClassLoader(cl); 883 if (mCurMap != null) { 884 mCurMap.setClassLoader(cl); 885 } 886 receiver.setOrderedHint(true); 887 receiver.setResult(mCurCode, mCurData, mCurMap); 888 receiver.clearAbortBroadcast(); 889 receiver.setOrderedHint(mCurOrdered); 890 receiver.setInitialStickyHint(mCurSticky); 891 receiver.onReceive(mContext, intent); 892 } catch (Exception e) { 893 if (mRegistered && mCurOrdered) { 894 try { 895 if (DEBUG_BROADCAST) Slog.i(TAG, 896 "Finishing failed broadcast to " + mReceiver); 897 mgr.finishReceiver(mIIntentReceiver, 898 mCurCode, mCurData, mCurMap, false); 899 } catch (RemoteException ex) { 900 } 901 } 902 if (mInstrumentation == null || 903 !mInstrumentation.onException(mReceiver, e)) { 904 throw new RuntimeException( 905 "Error receiving broadcast " + intent 906 + " in " + mReceiver, e); 907 } 908 } 909 if (mRegistered && mCurOrdered) { 910 try { 911 if (DEBUG_BROADCAST) Slog.i(TAG, 912 "Finishing broadcast to " + mReceiver); 913 mgr.finishReceiver(mIIntentReceiver, 914 receiver.getResultCode(), 915 receiver.getResultData(), 916 receiver.getResultExtras(false), 917 receiver.getAbortBroadcast()); 918 } catch (RemoteException ex) { 919 } 920 } 921 } 922 } 923 924 ReceiverDispatcher(BroadcastReceiver receiver, Context context, 925 Handler activityThread, Instrumentation instrumentation, 926 boolean registered) { 927 if (activityThread == null) { 928 throw new NullPointerException("Handler must not be null"); 929 } 930 931 mIIntentReceiver = new InnerReceiver(this, !registered); 932 mReceiver = receiver; 933 mContext = context; 934 mActivityThread = activityThread; 935 mInstrumentation = instrumentation; 936 mRegistered = registered; 937 mLocation = new IntentReceiverLeaked(null); 938 mLocation.fillInStackTrace(); 939 } 940 941 void validate(Context context, Handler activityThread) { 942 if (mContext != context) { 943 throw new IllegalStateException( 944 "Receiver " + mReceiver + 945 " registered with differing Context (was " + 946 mContext + " now " + context + ")"); 947 } 948 if (mActivityThread != activityThread) { 949 throw new IllegalStateException( 950 "Receiver " + mReceiver + 951 " registered with differing handler (was " + 952 mActivityThread + " now " + activityThread + ")"); 953 } 954 } 955 956 IntentReceiverLeaked getLocation() { 957 return mLocation; 958 } 959 960 BroadcastReceiver getIntentReceiver() { 961 return mReceiver; 962 } 963 964 IIntentReceiver getIIntentReceiver() { 965 return mIIntentReceiver; 966 } 967 968 void setUnregisterLocation(RuntimeException ex) { 969 mUnregisterLocation = ex; 970 } 971 972 RuntimeException getUnregisterLocation() { 973 return mUnregisterLocation; 974 } 975 976 public void performReceive(Intent intent, int resultCode, 977 String data, Bundle extras, boolean ordered, boolean sticky) { 978 if (DEBUG_BROADCAST) { 979 int seq = intent.getIntExtra("seq", -1); 980 Slog.i(TAG, "Enqueueing broadcast " + intent.getAction() + " seq=" + seq 981 + " to " + mReceiver); 982 } 983 Args args = new Args(); 984 args.mCurIntent = intent; 985 args.mCurCode = resultCode; 986 args.mCurData = data; 987 args.mCurMap = extras; 988 args.mCurOrdered = ordered; 989 args.mCurSticky = sticky; 990 if (!mActivityThread.post(args)) { 991 if (mRegistered && ordered) { 992 IActivityManager mgr = ActivityManagerNative.getDefault(); 993 try { 994 if (DEBUG_BROADCAST) Slog.i(TAG, 995 "Finishing sync broadcast to " + mReceiver); 996 mgr.finishReceiver(mIIntentReceiver, args.mCurCode, 997 args.mCurData, args.mCurMap, false); 998 } catch (RemoteException ex) { 999 } 1000 } 1001 } 1002 } 1003 1004 } 1005 1006 public final IServiceConnection getServiceDispatcher(ServiceConnection c, 1007 Context context, Handler handler, int flags) { 1008 synchronized (mServices) { 1009 ServiceDispatcher sd = null; 1010 HashMap<ServiceConnection, ServiceDispatcher> map = mServices.get(context); 1011 if (map != null) { 1012 sd = map.get(c); 1013 } 1014 if (sd == null) { 1015 sd = new ServiceDispatcher(c, context, handler, flags); 1016 if (map == null) { 1017 map = new HashMap<ServiceConnection, ServiceDispatcher>(); 1018 mServices.put(context, map); 1019 } 1020 map.put(c, sd); 1021 } else { 1022 sd.validate(context, handler); 1023 } 1024 return sd.getIServiceConnection(); 1025 } 1026 } 1027 1028 public final IServiceConnection forgetServiceDispatcher(Context context, 1029 ServiceConnection c) { 1030 synchronized (mServices) { 1031 HashMap<ServiceConnection, ServiceDispatcher> map 1032 = mServices.get(context); 1033 ServiceDispatcher sd = null; 1034 if (map != null) { 1035 sd = map.get(c); 1036 if (sd != null) { 1037 map.remove(c); 1038 sd.doForget(); 1039 if (map.size() == 0) { 1040 mServices.remove(context); 1041 } 1042 if ((sd.getFlags()&Context.BIND_DEBUG_UNBIND) != 0) { 1043 HashMap<ServiceConnection, ServiceDispatcher> holder 1044 = mUnboundServices.get(context); 1045 if (holder == null) { 1046 holder = new HashMap<ServiceConnection, ServiceDispatcher>(); 1047 mUnboundServices.put(context, holder); 1048 } 1049 RuntimeException ex = new IllegalArgumentException( 1050 "Originally unbound here:"); 1051 ex.fillInStackTrace(); 1052 sd.setUnbindLocation(ex); 1053 holder.put(c, sd); 1054 } 1055 return sd.getIServiceConnection(); 1056 } 1057 } 1058 HashMap<ServiceConnection, ServiceDispatcher> holder 1059 = mUnboundServices.get(context); 1060 if (holder != null) { 1061 sd = holder.get(c); 1062 if (sd != null) { 1063 RuntimeException ex = sd.getUnbindLocation(); 1064 throw new IllegalArgumentException( 1065 "Unbinding Service " + c 1066 + " that was already unbound", ex); 1067 } 1068 } 1069 if (context == null) { 1070 throw new IllegalStateException("Unbinding Service " + c 1071 + " from Context that is no longer in use: " + context); 1072 } else { 1073 throw new IllegalArgumentException("Service not registered: " + c); 1074 } 1075 } 1076 } 1077 1078 static final class ServiceDispatcher { 1079 private final InnerConnection mIServiceConnection; 1080 private final ServiceConnection mConnection; 1081 private final Context mContext; 1082 private final Handler mActivityThread; 1083 private final ServiceConnectionLeaked mLocation; 1084 private final int mFlags; 1085 1086 private RuntimeException mUnbindLocation; 1087 1088 private boolean mDied; 1089 1090 private static class ConnectionInfo { 1091 IBinder binder; 1092 IBinder.DeathRecipient deathMonitor; 1093 } 1094 1095 private static class InnerConnection extends IServiceConnection.Stub { 1096 final WeakReference<ServiceDispatcher> mDispatcher; 1097 1098 InnerConnection(ServiceDispatcher sd) { 1099 mDispatcher = new WeakReference<ServiceDispatcher>(sd); 1100 } 1101 1102 public void connected(ComponentName name, IBinder service) throws RemoteException { 1103 ServiceDispatcher sd = mDispatcher.get(); 1104 if (sd != null) { 1105 sd.connected(name, service); 1106 } 1107 } 1108 } 1109 1110 private final HashMap<ComponentName, ConnectionInfo> mActiveConnections 1111 = new HashMap<ComponentName, ConnectionInfo>(); 1112 1113 ServiceDispatcher(ServiceConnection conn, 1114 Context context, Handler activityThread, int flags) { 1115 mIServiceConnection = new InnerConnection(this); 1116 mConnection = conn; 1117 mContext = context; 1118 mActivityThread = activityThread; 1119 mLocation = new ServiceConnectionLeaked(null); 1120 mLocation.fillInStackTrace(); 1121 mFlags = flags; 1122 } 1123 1124 void validate(Context context, Handler activityThread) { 1125 if (mContext != context) { 1126 throw new RuntimeException( 1127 "ServiceConnection " + mConnection + 1128 " registered with differing Context (was " + 1129 mContext + " now " + context + ")"); 1130 } 1131 if (mActivityThread != activityThread) { 1132 throw new RuntimeException( 1133 "ServiceConnection " + mConnection + 1134 " registered with differing handler (was " + 1135 mActivityThread + " now " + activityThread + ")"); 1136 } 1137 } 1138 1139 void doForget() { 1140 synchronized(this) { 1141 Iterator<ConnectionInfo> it = mActiveConnections.values().iterator(); 1142 while (it.hasNext()) { 1143 ConnectionInfo ci = it.next(); 1144 ci.binder.unlinkToDeath(ci.deathMonitor, 0); 1145 } 1146 mActiveConnections.clear(); 1147 } 1148 } 1149 1150 ServiceConnectionLeaked getLocation() { 1151 return mLocation; 1152 } 1153 1154 ServiceConnection getServiceConnection() { 1155 return mConnection; 1156 } 1157 1158 IServiceConnection getIServiceConnection() { 1159 return mIServiceConnection; 1160 } 1161 1162 int getFlags() { 1163 return mFlags; 1164 } 1165 1166 void setUnbindLocation(RuntimeException ex) { 1167 mUnbindLocation = ex; 1168 } 1169 1170 RuntimeException getUnbindLocation() { 1171 return mUnbindLocation; 1172 } 1173 1174 public void connected(ComponentName name, IBinder service) { 1175 if (mActivityThread != null) { 1176 mActivityThread.post(new RunConnection(name, service, 0)); 1177 } else { 1178 doConnected(name, service); 1179 } 1180 } 1181 1182 public void death(ComponentName name, IBinder service) { 1183 ConnectionInfo old; 1184 1185 synchronized (this) { 1186 mDied = true; 1187 old = mActiveConnections.remove(name); 1188 if (old == null || old.binder != service) { 1189 // Death for someone different than who we last 1190 // reported... just ignore it. 1191 return; 1192 } 1193 old.binder.unlinkToDeath(old.deathMonitor, 0); 1194 } 1195 1196 if (mActivityThread != null) { 1197 mActivityThread.post(new RunConnection(name, service, 1)); 1198 } else { 1199 doDeath(name, service); 1200 } 1201 } 1202 1203 public void doConnected(ComponentName name, IBinder service) { 1204 ConnectionInfo old; 1205 ConnectionInfo info; 1206 1207 synchronized (this) { 1208 old = mActiveConnections.get(name); 1209 if (old != null && old.binder == service) { 1210 // Huh, already have this one. Oh well! 1211 return; 1212 } 1213 1214 if (service != null) { 1215 // A new service is being connected... set it all up. 1216 mDied = false; 1217 info = new ConnectionInfo(); 1218 info.binder = service; 1219 info.deathMonitor = new DeathMonitor(name, service); 1220 try { 1221 service.linkToDeath(info.deathMonitor, 0); 1222 mActiveConnections.put(name, info); 1223 } catch (RemoteException e) { 1224 // This service was dead before we got it... just 1225 // don't do anything with it. 1226 mActiveConnections.remove(name); 1227 return; 1228 } 1229 1230 } else { 1231 // The named service is being disconnected... clean up. 1232 mActiveConnections.remove(name); 1233 } 1234 1235 if (old != null) { 1236 old.binder.unlinkToDeath(old.deathMonitor, 0); 1237 } 1238 } 1239 1240 // If there was an old service, it is not disconnected. 1241 if (old != null) { 1242 mConnection.onServiceDisconnected(name); 1243 } 1244 // If there is a new service, it is now connected. 1245 if (service != null) { 1246 mConnection.onServiceConnected(name, service); 1247 } 1248 } 1249 1250 public void doDeath(ComponentName name, IBinder service) { 1251 mConnection.onServiceDisconnected(name); 1252 } 1253 1254 private final class RunConnection implements Runnable { 1255 RunConnection(ComponentName name, IBinder service, int command) { 1256 mName = name; 1257 mService = service; 1258 mCommand = command; 1259 } 1260 1261 public void run() { 1262 if (mCommand == 0) { 1263 doConnected(mName, mService); 1264 } else if (mCommand == 1) { 1265 doDeath(mName, mService); 1266 } 1267 } 1268 1269 final ComponentName mName; 1270 final IBinder mService; 1271 final int mCommand; 1272 } 1273 1274 private final class DeathMonitor implements IBinder.DeathRecipient 1275 { 1276 DeathMonitor(ComponentName name, IBinder service) { 1277 mName = name; 1278 mService = service; 1279 } 1280 1281 public void binderDied() { 1282 death(mName, mService); 1283 } 1284 1285 final ComponentName mName; 1286 final IBinder mService; 1287 } 1288 } 1289 } 1290 1291 private static ContextImpl mSystemContext = null; 1292 1293 private static final class ActivityRecord { 1294 IBinder token; 1295 int ident; 1296 Intent intent; 1297 Bundle state; 1298 Activity activity; 1299 Window window; 1300 Activity parent; 1301 String embeddedID; 1302 Object lastNonConfigurationInstance; 1303 HashMap<String,Object> lastNonConfigurationChildInstances; 1304 boolean paused; 1305 boolean stopped; 1306 boolean hideForNow; 1307 Configuration newConfig; 1308 Configuration createdConfig; 1309 ActivityRecord nextIdle; 1310 1311 ActivityInfo activityInfo; 1312 PackageInfo packageInfo; 1313 1314 List<ResultInfo> pendingResults; 1315 List<Intent> pendingIntents; 1316 1317 boolean startsNotResumed; 1318 boolean isForward; 1319 1320 ActivityRecord() { 1321 parent = null; 1322 embeddedID = null; 1323 paused = false; 1324 stopped = false; 1325 hideForNow = false; 1326 nextIdle = null; 1327 } 1328 1329 public String toString() { 1330 ComponentName componentName = intent.getComponent(); 1331 return "ActivityRecord{" 1332 + Integer.toHexString(System.identityHashCode(this)) 1333 + " token=" + token + " " + (componentName == null 1334 ? "no component name" : componentName.toShortString()) 1335 + "}"; 1336 } 1337 } 1338 1339 private final class ProviderRecord implements IBinder.DeathRecipient { 1340 final String mName; 1341 final IContentProvider mProvider; 1342 final ContentProvider mLocalProvider; 1343 1344 ProviderRecord(String name, IContentProvider provider, 1345 ContentProvider localProvider) { 1346 mName = name; 1347 mProvider = provider; 1348 mLocalProvider = localProvider; 1349 } 1350 1351 public void binderDied() { 1352 removeDeadProvider(mName, mProvider); 1353 } 1354 } 1355 1356 private static final class NewIntentData { 1357 List<Intent> intents; 1358 IBinder token; 1359 public String toString() { 1360 return "NewIntentData{intents=" + intents + " token=" + token + "}"; 1361 } 1362 } 1363 1364 private static final class ReceiverData { 1365 Intent intent; 1366 ActivityInfo info; 1367 int resultCode; 1368 String resultData; 1369 Bundle resultExtras; 1370 boolean sync; 1371 boolean resultAbort; 1372 public String toString() { 1373 return "ReceiverData{intent=" + intent + " packageName=" + 1374 info.packageName + " resultCode=" + resultCode 1375 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}"; 1376 } 1377 } 1378 1379 private static final class CreateBackupAgentData { 1380 ApplicationInfo appInfo; 1381 int backupMode; 1382 public String toString() { 1383 return "CreateBackupAgentData{appInfo=" + appInfo 1384 + " backupAgent=" + appInfo.backupAgentName 1385 + " mode=" + backupMode + "}"; 1386 } 1387 } 1388 1389 private static final class CreateServiceData { 1390 IBinder token; 1391 ServiceInfo info; 1392 Intent intent; 1393 public String toString() { 1394 return "CreateServiceData{token=" + token + " className=" 1395 + info.name + " packageName=" + info.packageName 1396 + " intent=" + intent + "}"; 1397 } 1398 } 1399 1400 private static final class BindServiceData { 1401 IBinder token; 1402 Intent intent; 1403 boolean rebind; 1404 public String toString() { 1405 return "BindServiceData{token=" + token + " intent=" + intent + "}"; 1406 } 1407 } 1408 1409 private static final class ServiceArgsData { 1410 IBinder token; 1411 int startId; 1412 int flags; 1413 Intent args; 1414 public String toString() { 1415 return "ServiceArgsData{token=" + token + " startId=" + startId 1416 + " args=" + args + "}"; 1417 } 1418 } 1419 1420 private static final class AppBindData { 1421 PackageInfo info; 1422 String processName; 1423 ApplicationInfo appInfo; 1424 List<ProviderInfo> providers; 1425 ComponentName instrumentationName; 1426 String profileFile; 1427 Bundle instrumentationArgs; 1428 IInstrumentationWatcher instrumentationWatcher; 1429 int debugMode; 1430 boolean restrictedBackupMode; 1431 Configuration config; 1432 boolean handlingProfiling; 1433 public String toString() { 1434 return "AppBindData{appInfo=" + appInfo + "}"; 1435 } 1436 } 1437 1438 private static final class DumpServiceInfo { 1439 FileDescriptor fd; 1440 IBinder service; 1441 String[] args; 1442 boolean dumped; 1443 } 1444 1445 private static final class ResultData { 1446 IBinder token; 1447 List<ResultInfo> results; 1448 public String toString() { 1449 return "ResultData{token=" + token + " results" + results + "}"; 1450 } 1451 } 1452 1453 private static final class ContextCleanupInfo { 1454 ContextImpl context; 1455 String what; 1456 String who; 1457 } 1458 1459 private static final class ProfilerControlData { 1460 String path; 1461 ParcelFileDescriptor fd; 1462 } 1463 1464 private final class ApplicationThread extends ApplicationThreadNative { 1465 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s"; 1466 private static final String ONE_COUNT_COLUMN = "%17s %8d"; 1467 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d"; 1468 private static final String DB_INFO_FORMAT = " %8d %8d %10d %s"; 1469 1470 // Formatting for checkin service - update version if row format changes 1471 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1; 1472 1473 public final void schedulePauseActivity(IBinder token, boolean finished, 1474 boolean userLeaving, int configChanges) { 1475 queueOrSendMessage( 1476 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY, 1477 token, 1478 (userLeaving ? 1 : 0), 1479 configChanges); 1480 } 1481 1482 public final void scheduleStopActivity(IBinder token, boolean showWindow, 1483 int configChanges) { 1484 queueOrSendMessage( 1485 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE, 1486 token, 0, configChanges); 1487 } 1488 1489 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) { 1490 queueOrSendMessage( 1491 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW, 1492 token); 1493 } 1494 1495 public final void scheduleResumeActivity(IBinder token, boolean isForward) { 1496 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0); 1497 } 1498 1499 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) { 1500 ResultData res = new ResultData(); 1501 res.token = token; 1502 res.results = results; 1503 queueOrSendMessage(H.SEND_RESULT, res); 1504 } 1505 1506 // we use token to identify this activity without having to send the 1507 // activity itself back to the activity manager. (matters more with ipc) 1508 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, 1509 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults, 1510 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) { 1511 ActivityRecord r = new ActivityRecord(); 1512 1513 r.token = token; 1514 r.ident = ident; 1515 r.intent = intent; 1516 r.activityInfo = info; 1517 r.state = state; 1518 1519 r.pendingResults = pendingResults; 1520 r.pendingIntents = pendingNewIntents; 1521 1522 r.startsNotResumed = notResumed; 1523 r.isForward = isForward; 1524 1525 queueOrSendMessage(H.LAUNCH_ACTIVITY, r); 1526 } 1527 1528 public final void scheduleRelaunchActivity(IBinder token, 1529 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents, 1530 int configChanges, boolean notResumed, Configuration config) { 1531 ActivityRecord r = new ActivityRecord(); 1532 1533 r.token = token; 1534 r.pendingResults = pendingResults; 1535 r.pendingIntents = pendingNewIntents; 1536 r.startsNotResumed = notResumed; 1537 r.createdConfig = config; 1538 1539 synchronized (mPackages) { 1540 mRelaunchingActivities.add(r); 1541 } 1542 1543 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges); 1544 } 1545 1546 public final void scheduleNewIntent(List<Intent> intents, IBinder token) { 1547 NewIntentData data = new NewIntentData(); 1548 data.intents = intents; 1549 data.token = token; 1550 1551 queueOrSendMessage(H.NEW_INTENT, data); 1552 } 1553 1554 public final void scheduleDestroyActivity(IBinder token, boolean finishing, 1555 int configChanges) { 1556 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0, 1557 configChanges); 1558 } 1559 1560 public final void scheduleReceiver(Intent intent, ActivityInfo info, 1561 int resultCode, String data, Bundle extras, boolean sync) { 1562 ReceiverData r = new ReceiverData(); 1563 1564 r.intent = intent; 1565 r.info = info; 1566 r.resultCode = resultCode; 1567 r.resultData = data; 1568 r.resultExtras = extras; 1569 r.sync = sync; 1570 1571 queueOrSendMessage(H.RECEIVER, r); 1572 } 1573 1574 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) { 1575 CreateBackupAgentData d = new CreateBackupAgentData(); 1576 d.appInfo = app; 1577 d.backupMode = backupMode; 1578 1579 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d); 1580 } 1581 1582 public final void scheduleDestroyBackupAgent(ApplicationInfo app) { 1583 CreateBackupAgentData d = new CreateBackupAgentData(); 1584 d.appInfo = app; 1585 1586 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d); 1587 } 1588 1589 public final void scheduleCreateService(IBinder token, 1590 ServiceInfo info) { 1591 CreateServiceData s = new CreateServiceData(); 1592 s.token = token; 1593 s.info = info; 1594 1595 queueOrSendMessage(H.CREATE_SERVICE, s); 1596 } 1597 1598 public final void scheduleBindService(IBinder token, Intent intent, 1599 boolean rebind) { 1600 BindServiceData s = new BindServiceData(); 1601 s.token = token; 1602 s.intent = intent; 1603 s.rebind = rebind; 1604 1605 queueOrSendMessage(H.BIND_SERVICE, s); 1606 } 1607 1608 public final void scheduleUnbindService(IBinder token, Intent intent) { 1609 BindServiceData s = new BindServiceData(); 1610 s.token = token; 1611 s.intent = intent; 1612 1613 queueOrSendMessage(H.UNBIND_SERVICE, s); 1614 } 1615 1616 public final void scheduleServiceArgs(IBinder token, int startId, 1617 int flags ,Intent args) { 1618 ServiceArgsData s = new ServiceArgsData(); 1619 s.token = token; 1620 s.startId = startId; 1621 s.flags = flags; 1622 s.args = args; 1623 1624 queueOrSendMessage(H.SERVICE_ARGS, s); 1625 } 1626 1627 public final void scheduleStopService(IBinder token) { 1628 queueOrSendMessage(H.STOP_SERVICE, token); 1629 } 1630 1631 public final void bindApplication(String processName, 1632 ApplicationInfo appInfo, List<ProviderInfo> providers, 1633 ComponentName instrumentationName, String profileFile, 1634 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher, 1635 int debugMode, boolean isRestrictedBackupMode, Configuration config, 1636 Map<String, IBinder> services) { 1637 1638 if (services != null) { 1639 // Setup the service cache in the ServiceManager 1640 ServiceManager.initServiceCache(services); 1641 } 1642 1643 AppBindData data = new AppBindData(); 1644 data.processName = processName; 1645 data.appInfo = appInfo; 1646 data.providers = providers; 1647 data.instrumentationName = instrumentationName; 1648 data.profileFile = profileFile; 1649 data.instrumentationArgs = instrumentationArgs; 1650 data.instrumentationWatcher = instrumentationWatcher; 1651 data.debugMode = debugMode; 1652 data.restrictedBackupMode = isRestrictedBackupMode; 1653 data.config = config; 1654 queueOrSendMessage(H.BIND_APPLICATION, data); 1655 } 1656 1657 public final void scheduleExit() { 1658 queueOrSendMessage(H.EXIT_APPLICATION, null); 1659 } 1660 1661 public final void scheduleSuicide() { 1662 queueOrSendMessage(H.SUICIDE, null); 1663 } 1664 1665 public void requestThumbnail(IBinder token) { 1666 queueOrSendMessage(H.REQUEST_THUMBNAIL, token); 1667 } 1668 1669 public void scheduleConfigurationChanged(Configuration config) { 1670 synchronized (mPackages) { 1671 if (mPendingConfiguration == null || 1672 mPendingConfiguration.isOtherSeqNewer(config)) { 1673 mPendingConfiguration = config; 1674 } 1675 } 1676 queueOrSendMessage(H.CONFIGURATION_CHANGED, config); 1677 } 1678 1679 public void updateTimeZone() { 1680 TimeZone.setDefault(null); 1681 } 1682 1683 public void processInBackground() { 1684 mH.removeMessages(H.GC_WHEN_IDLE); 1685 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE)); 1686 } 1687 1688 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) { 1689 DumpServiceInfo data = new DumpServiceInfo(); 1690 data.fd = fd; 1691 data.service = servicetoken; 1692 data.args = args; 1693 data.dumped = false; 1694 queueOrSendMessage(H.DUMP_SERVICE, data); 1695 synchronized (data) { 1696 while (!data.dumped) { 1697 try { 1698 data.wait(); 1699 } catch (InterruptedException e) { 1700 // no need to do anything here, we will keep waiting until 1701 // dumped is set 1702 } 1703 } 1704 } 1705 } 1706 1707 // This function exists to make sure all receiver dispatching is 1708 // correctly ordered, since these are one-way calls and the binder driver 1709 // applies transaction ordering per object for such calls. 1710 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent, 1711 int resultCode, String dataStr, Bundle extras, boolean ordered, 1712 boolean sticky) throws RemoteException { 1713 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky); 1714 } 1715 1716 public void scheduleLowMemory() { 1717 queueOrSendMessage(H.LOW_MEMORY, null); 1718 } 1719 1720 public void scheduleActivityConfigurationChanged(IBinder token) { 1721 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token); 1722 } 1723 1724 public void requestPss() { 1725 try { 1726 ActivityManagerNative.getDefault().reportPss(this, 1727 (int)Process.getPss(Process.myPid())); 1728 } catch (RemoteException e) { 1729 } 1730 } 1731 1732 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) { 1733 ProfilerControlData pcd = new ProfilerControlData(); 1734 pcd.path = path; 1735 pcd.fd = fd; 1736 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0); 1737 } 1738 1739 public void setSchedulingGroup(int group) { 1740 // Note: do this immediately, since going into the foreground 1741 // should happen regardless of what pending work we have to do 1742 // and the activity manager will wait for us to report back that 1743 // we are done before sending us to the background. 1744 try { 1745 Process.setProcessGroup(Process.myPid(), group); 1746 } catch (Exception e) { 1747 Slog.w(TAG, "Failed setting process group to " + group, e); 1748 } 1749 } 1750 1751 public void getMemoryInfo(Debug.MemoryInfo outInfo) { 1752 Debug.getMemoryInfo(outInfo); 1753 } 1754 1755 @Override 1756 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1757 long nativeMax = Debug.getNativeHeapSize() / 1024; 1758 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024; 1759 long nativeFree = Debug.getNativeHeapFreeSize() / 1024; 1760 1761 Debug.MemoryInfo memInfo = new Debug.MemoryInfo(); 1762 Debug.getMemoryInfo(memInfo); 1763 1764 final int nativeShared = memInfo.nativeSharedDirty; 1765 final int dalvikShared = memInfo.dalvikSharedDirty; 1766 final int otherShared = memInfo.otherSharedDirty; 1767 1768 final int nativePrivate = memInfo.nativePrivateDirty; 1769 final int dalvikPrivate = memInfo.dalvikPrivateDirty; 1770 final int otherPrivate = memInfo.otherPrivateDirty; 1771 1772 Runtime runtime = Runtime.getRuntime(); 1773 1774 long dalvikMax = runtime.totalMemory() / 1024; 1775 long dalvikFree = runtime.freeMemory() / 1024; 1776 long dalvikAllocated = dalvikMax - dalvikFree; 1777 long viewInstanceCount = ViewDebug.getViewInstanceCount(); 1778 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount(); 1779 long appContextInstanceCount = ContextImpl.getInstanceCount(); 1780 long activityInstanceCount = Activity.getInstanceCount(); 1781 int globalAssetCount = AssetManager.getGlobalAssetCount(); 1782 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount(); 1783 int binderLocalObjectCount = Debug.getBinderLocalObjectCount(); 1784 int binderProxyObjectCount = Debug.getBinderProxyObjectCount(); 1785 int binderDeathObjectCount = Debug.getBinderDeathObjectCount(); 1786 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount(); 1787 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024; 1788 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo(); 1789 1790 // Check to see if we were called by checkin server. If so, print terse format. 1791 boolean doCheckinFormat = false; 1792 if (args != null) { 1793 for (String arg : args) { 1794 if ("-c".equals(arg)) doCheckinFormat = true; 1795 } 1796 } 1797 1798 // For checkin, we print one long comma-separated list of values 1799 if (doCheckinFormat) { 1800 // NOTE: if you change anything significant below, also consider changing 1801 // ACTIVITY_THREAD_CHECKIN_VERSION. 1802 String processName = (mBoundApplication != null) 1803 ? mBoundApplication.processName : "unknown"; 1804 1805 // Header 1806 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(','); 1807 pw.print(Process.myPid()); pw.print(','); 1808 pw.print(processName); pw.print(','); 1809 1810 // Heap info - max 1811 pw.print(nativeMax); pw.print(','); 1812 pw.print(dalvikMax); pw.print(','); 1813 pw.print("N/A,"); 1814 pw.print(nativeMax + dalvikMax); pw.print(','); 1815 1816 // Heap info - allocated 1817 pw.print(nativeAllocated); pw.print(','); 1818 pw.print(dalvikAllocated); pw.print(','); 1819 pw.print("N/A,"); 1820 pw.print(nativeAllocated + dalvikAllocated); pw.print(','); 1821 1822 // Heap info - free 1823 pw.print(nativeFree); pw.print(','); 1824 pw.print(dalvikFree); pw.print(','); 1825 pw.print("N/A,"); 1826 pw.print(nativeFree + dalvikFree); pw.print(','); 1827 1828 // Heap info - proportional set size 1829 pw.print(memInfo.nativePss); pw.print(','); 1830 pw.print(memInfo.dalvikPss); pw.print(','); 1831 pw.print(memInfo.otherPss); pw.print(','); 1832 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(','); 1833 1834 // Heap info - shared 1835 pw.print(nativeShared); pw.print(','); 1836 pw.print(dalvikShared); pw.print(','); 1837 pw.print(otherShared); pw.print(','); 1838 pw.print(nativeShared + dalvikShared + otherShared); pw.print(','); 1839 1840 // Heap info - private 1841 pw.print(nativePrivate); pw.print(','); 1842 pw.print(dalvikPrivate); pw.print(','); 1843 pw.print(otherPrivate); pw.print(','); 1844 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(','); 1845 1846 // Object counts 1847 pw.print(viewInstanceCount); pw.print(','); 1848 pw.print(viewRootInstanceCount); pw.print(','); 1849 pw.print(appContextInstanceCount); pw.print(','); 1850 pw.print(activityInstanceCount); pw.print(','); 1851 1852 pw.print(globalAssetCount); pw.print(','); 1853 pw.print(globalAssetManagerCount); pw.print(','); 1854 pw.print(binderLocalObjectCount); pw.print(','); 1855 pw.print(binderProxyObjectCount); pw.print(','); 1856 1857 pw.print(binderDeathObjectCount); pw.print(','); 1858 pw.print(openSslSocketCount); pw.print(','); 1859 1860 // SQL 1861 pw.print(sqliteAllocated); pw.print(','); 1862 pw.print(stats.memoryUsed / 1024); pw.print(','); 1863 pw.print(stats.pageCacheOverflo / 1024); pw.print(','); 1864 pw.print(stats.largestMemAlloc / 1024); pw.print(','); 1865 for (int i = 0; i < stats.dbStats.size(); i++) { 1866 DbStats dbStats = stats.dbStats.get(i); 1867 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize, 1868 dbStats.lookaside, dbStats.dbName); 1869 pw.print(','); 1870 } 1871 1872 return; 1873 } 1874 1875 // otherwise, show human-readable format 1876 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total"); 1877 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax); 1878 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A", 1879 nativeAllocated + dalvikAllocated); 1880 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A", 1881 nativeFree + dalvikFree); 1882 1883 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss, 1884 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); 1885 1886 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared, 1887 nativeShared + dalvikShared + otherShared); 1888 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate, 1889 nativePrivate + dalvikPrivate + otherPrivate); 1890 1891 pw.println(" "); 1892 pw.println(" Objects"); 1893 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:", 1894 viewRootInstanceCount); 1895 1896 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount, 1897 "Activities:", activityInstanceCount); 1898 1899 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount, 1900 "AssetManagers:", globalAssetManagerCount); 1901 1902 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount, 1903 "Proxy Binders:", binderProxyObjectCount); 1904 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount); 1905 1906 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount); 1907 1908 // SQLite mem info 1909 pw.println(" "); 1910 pw.println(" SQL"); 1911 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "memoryUsed:", 1912 stats.memoryUsed / 1024); 1913 printRow(pw, TWO_COUNT_COLUMNS, "pageCacheOverflo:", stats.pageCacheOverflo / 1024, 1914 "largestMemAlloc:", stats.largestMemAlloc / 1024); 1915 pw.println(" "); 1916 int N = stats.dbStats.size(); 1917 if (N > 0) { 1918 pw.println(" DATABASES"); 1919 printRow(pw, " %8s %8s %10s %s", "Pagesize", "Dbsize", "Lookaside", "Dbname"); 1920 for (int i = 0; i < N; i++) { 1921 DbStats dbStats = stats.dbStats.get(i); 1922 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize, 1923 dbStats.lookaside, dbStats.dbName); 1924 } 1925 } 1926 1927 // Asset details. 1928 String assetAlloc = AssetManager.getAssetAllocations(); 1929 if (assetAlloc != null) { 1930 pw.println(" "); 1931 pw.println(" Asset Allocations"); 1932 pw.print(assetAlloc); 1933 } 1934 } 1935 1936 private void printRow(PrintWriter pw, String format, Object...objs) { 1937 pw.println(String.format(format, objs)); 1938 } 1939 } 1940 1941 private final class H extends Handler { 1942 private H() { 1943 SamplingProfiler.getInstance().setEventThread(mLooper.getThread()); 1944 } 1945 1946 public static final int LAUNCH_ACTIVITY = 100; 1947 public static final int PAUSE_ACTIVITY = 101; 1948 public static final int PAUSE_ACTIVITY_FINISHING= 102; 1949 public static final int STOP_ACTIVITY_SHOW = 103; 1950 public static final int STOP_ACTIVITY_HIDE = 104; 1951 public static final int SHOW_WINDOW = 105; 1952 public static final int HIDE_WINDOW = 106; 1953 public static final int RESUME_ACTIVITY = 107; 1954 public static final int SEND_RESULT = 108; 1955 public static final int DESTROY_ACTIVITY = 109; 1956 public static final int BIND_APPLICATION = 110; 1957 public static final int EXIT_APPLICATION = 111; 1958 public static final int NEW_INTENT = 112; 1959 public static final int RECEIVER = 113; 1960 public static final int CREATE_SERVICE = 114; 1961 public static final int SERVICE_ARGS = 115; 1962 public static final int STOP_SERVICE = 116; 1963 public static final int REQUEST_THUMBNAIL = 117; 1964 public static final int CONFIGURATION_CHANGED = 118; 1965 public static final int CLEAN_UP_CONTEXT = 119; 1966 public static final int GC_WHEN_IDLE = 120; 1967 public static final int BIND_SERVICE = 121; 1968 public static final int UNBIND_SERVICE = 122; 1969 public static final int DUMP_SERVICE = 123; 1970 public static final int LOW_MEMORY = 124; 1971 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125; 1972 public static final int RELAUNCH_ACTIVITY = 126; 1973 public static final int PROFILER_CONTROL = 127; 1974 public static final int CREATE_BACKUP_AGENT = 128; 1975 public static final int DESTROY_BACKUP_AGENT = 129; 1976 public static final int SUICIDE = 130; 1977 public static final int REMOVE_PROVIDER = 131; 1978 public static final int ENABLE_JIT = 132; 1979 String codeToString(int code) { 1980 if (localLOGV) { 1981 switch (code) { 1982 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY"; 1983 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY"; 1984 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING"; 1985 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW"; 1986 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE"; 1987 case SHOW_WINDOW: return "SHOW_WINDOW"; 1988 case HIDE_WINDOW: return "HIDE_WINDOW"; 1989 case RESUME_ACTIVITY: return "RESUME_ACTIVITY"; 1990 case SEND_RESULT: return "SEND_RESULT"; 1991 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY"; 1992 case BIND_APPLICATION: return "BIND_APPLICATION"; 1993 case EXIT_APPLICATION: return "EXIT_APPLICATION"; 1994 case NEW_INTENT: return "NEW_INTENT"; 1995 case RECEIVER: return "RECEIVER"; 1996 case CREATE_SERVICE: return "CREATE_SERVICE"; 1997 case SERVICE_ARGS: return "SERVICE_ARGS"; 1998 case STOP_SERVICE: return "STOP_SERVICE"; 1999 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL"; 2000 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED"; 2001 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT"; 2002 case GC_WHEN_IDLE: return "GC_WHEN_IDLE"; 2003 case BIND_SERVICE: return "BIND_SERVICE"; 2004 case UNBIND_SERVICE: return "UNBIND_SERVICE"; 2005 case DUMP_SERVICE: return "DUMP_SERVICE"; 2006 case LOW_MEMORY: return "LOW_MEMORY"; 2007 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED"; 2008 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY"; 2009 case PROFILER_CONTROL: return "PROFILER_CONTROL"; 2010 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT"; 2011 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT"; 2012 case SUICIDE: return "SUICIDE"; 2013 case REMOVE_PROVIDER: return "REMOVE_PROVIDER"; 2014 case ENABLE_JIT: return "ENABLE_JIT"; 2015 } 2016 } 2017 return "(unknown)"; 2018 } 2019 public void handleMessage(Message msg) { 2020 switch (msg.what) { 2021 case LAUNCH_ACTIVITY: { 2022 ActivityRecord r = (ActivityRecord)msg.obj; 2023 2024 r.packageInfo = getPackageInfoNoCheck( 2025 r.activityInfo.applicationInfo); 2026 handleLaunchActivity(r, null); 2027 } break; 2028 case RELAUNCH_ACTIVITY: { 2029 ActivityRecord r = (ActivityRecord)msg.obj; 2030 handleRelaunchActivity(r, msg.arg1); 2031 } break; 2032 case PAUSE_ACTIVITY: 2033 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2); 2034 maybeSnapshot(); 2035 break; 2036 case PAUSE_ACTIVITY_FINISHING: 2037 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2); 2038 break; 2039 case STOP_ACTIVITY_SHOW: 2040 handleStopActivity((IBinder)msg.obj, true, msg.arg2); 2041 break; 2042 case STOP_ACTIVITY_HIDE: 2043 handleStopActivity((IBinder)msg.obj, false, msg.arg2); 2044 break; 2045 case SHOW_WINDOW: 2046 handleWindowVisibility((IBinder)msg.obj, true); 2047 break; 2048 case HIDE_WINDOW: 2049 handleWindowVisibility((IBinder)msg.obj, false); 2050 break; 2051 case RESUME_ACTIVITY: 2052 handleResumeActivity((IBinder)msg.obj, true, 2053 msg.arg1 != 0); 2054 break; 2055 case SEND_RESULT: 2056 handleSendResult((ResultData)msg.obj); 2057 break; 2058 case DESTROY_ACTIVITY: 2059 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0, 2060 msg.arg2, false); 2061 break; 2062 case BIND_APPLICATION: 2063 AppBindData data = (AppBindData)msg.obj; 2064 handleBindApplication(data); 2065 break; 2066 case EXIT_APPLICATION: 2067 if (mInitialApplication != null) { 2068 mInitialApplication.onTerminate(); 2069 } 2070 Looper.myLooper().quit(); 2071 break; 2072 case NEW_INTENT: 2073 handleNewIntent((NewIntentData)msg.obj); 2074 break; 2075 case RECEIVER: 2076 handleReceiver((ReceiverData)msg.obj); 2077 maybeSnapshot(); 2078 break; 2079 case CREATE_SERVICE: 2080 handleCreateService((CreateServiceData)msg.obj); 2081 break; 2082 case BIND_SERVICE: 2083 handleBindService((BindServiceData)msg.obj); 2084 break; 2085 case UNBIND_SERVICE: 2086 handleUnbindService((BindServiceData)msg.obj); 2087 break; 2088 case SERVICE_ARGS: 2089 handleServiceArgs((ServiceArgsData)msg.obj); 2090 break; 2091 case STOP_SERVICE: 2092 handleStopService((IBinder)msg.obj); 2093 maybeSnapshot(); 2094 break; 2095 case REQUEST_THUMBNAIL: 2096 handleRequestThumbnail((IBinder)msg.obj); 2097 break; 2098 case CONFIGURATION_CHANGED: 2099 handleConfigurationChanged((Configuration)msg.obj); 2100 break; 2101 case CLEAN_UP_CONTEXT: 2102 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj; 2103 cci.context.performFinalCleanup(cci.who, cci.what); 2104 break; 2105 case GC_WHEN_IDLE: 2106 scheduleGcIdler(); 2107 break; 2108 case DUMP_SERVICE: 2109 handleDumpService((DumpServiceInfo)msg.obj); 2110 break; 2111 case LOW_MEMORY: 2112 handleLowMemory(); 2113 break; 2114 case ACTIVITY_CONFIGURATION_CHANGED: 2115 handleActivityConfigurationChanged((IBinder)msg.obj); 2116 break; 2117 case PROFILER_CONTROL: 2118 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj); 2119 break; 2120 case CREATE_BACKUP_AGENT: 2121 handleCreateBackupAgent((CreateBackupAgentData)msg.obj); 2122 break; 2123 case DESTROY_BACKUP_AGENT: 2124 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj); 2125 break; 2126 case SUICIDE: 2127 Process.killProcess(Process.myPid()); 2128 break; 2129 case REMOVE_PROVIDER: 2130 completeRemoveProvider((IContentProvider)msg.obj); 2131 break; 2132 case ENABLE_JIT: 2133 ensureJitEnabled(); 2134 break; 2135 } 2136 } 2137 2138 void maybeSnapshot() { 2139 if (mBoundApplication != null) { 2140 SamplingProfilerIntegration.writeSnapshot( 2141 mBoundApplication.processName); 2142 } 2143 } 2144 } 2145 2146 private final class Idler implements MessageQueue.IdleHandler { 2147 public final boolean queueIdle() { 2148 ActivityRecord a = mNewActivities; 2149 if (a != null) { 2150 mNewActivities = null; 2151 IActivityManager am = ActivityManagerNative.getDefault(); 2152 ActivityRecord prev; 2153 do { 2154 if (localLOGV) Slog.v( 2155 TAG, "Reporting idle of " + a + 2156 " finished=" + 2157 (a.activity != null ? a.activity.mFinished : false)); 2158 if (a.activity != null && !a.activity.mFinished) { 2159 try { 2160 am.activityIdle(a.token, a.createdConfig); 2161 a.createdConfig = null; 2162 } catch (RemoteException ex) { 2163 } 2164 } 2165 prev = a; 2166 a = a.nextIdle; 2167 prev.nextIdle = null; 2168 } while (a != null); 2169 } 2170 ensureJitEnabled(); 2171 return false; 2172 } 2173 } 2174 2175 final class GcIdler implements MessageQueue.IdleHandler { 2176 public final boolean queueIdle() { 2177 doGcIfNeeded(); 2178 return false; 2179 } 2180 } 2181 2182 private final static class ResourcesKey { 2183 final private String mResDir; 2184 final private float mScale; 2185 final private int mHash; 2186 2187 ResourcesKey(String resDir, float scale) { 2188 mResDir = resDir; 2189 mScale = scale; 2190 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2); 2191 } 2192 2193 @Override 2194 public int hashCode() { 2195 return mHash; 2196 } 2197 2198 @Override 2199 public boolean equals(Object obj) { 2200 if (!(obj instanceof ResourcesKey)) { 2201 return false; 2202 } 2203 ResourcesKey peer = (ResourcesKey) obj; 2204 return mResDir.equals(peer.mResDir) && mScale == peer.mScale; 2205 } 2206 } 2207 2208 static IPackageManager sPackageManager; 2209 2210 final ApplicationThread mAppThread = new ApplicationThread(); 2211 final Looper mLooper = Looper.myLooper(); 2212 final H mH = new H(); 2213 final HashMap<IBinder, ActivityRecord> mActivities 2214 = new HashMap<IBinder, ActivityRecord>(); 2215 // List of new activities (via ActivityRecord.nextIdle) that should 2216 // be reported when next we idle. 2217 ActivityRecord mNewActivities = null; 2218 // Number of activities that are currently visible on-screen. 2219 int mNumVisibleActivities = 0; 2220 final HashMap<IBinder, Service> mServices 2221 = new HashMap<IBinder, Service>(); 2222 AppBindData mBoundApplication; 2223 Configuration mConfiguration; 2224 Configuration mResConfiguration; 2225 Application mInitialApplication; 2226 final ArrayList<Application> mAllApplications 2227 = new ArrayList<Application>(); 2228 // set of instantiated backup agents, keyed by package name 2229 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>(); 2230 static final ThreadLocal sThreadLocal = new ThreadLocal(); 2231 Instrumentation mInstrumentation; 2232 String mInstrumentationAppDir = null; 2233 String mInstrumentationAppPackage = null; 2234 String mInstrumentedAppDir = null; 2235 boolean mSystemThread = false; 2236 boolean mJitEnabled = false; 2237 2238 // These can be accessed by multiple threads; mPackages is the lock. 2239 // XXX For now we keep around information about all packages we have 2240 // seen, not removing entries from this map. 2241 final HashMap<String, WeakReference<PackageInfo>> mPackages 2242 = new HashMap<String, WeakReference<PackageInfo>>(); 2243 final HashMap<String, WeakReference<PackageInfo>> mResourcePackages 2244 = new HashMap<String, WeakReference<PackageInfo>>(); 2245 Display mDisplay = null; 2246 DisplayMetrics mDisplayMetrics = null; 2247 HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources 2248 = new HashMap<ResourcesKey, WeakReference<Resources> >(); 2249 final ArrayList<ActivityRecord> mRelaunchingActivities 2250 = new ArrayList<ActivityRecord>(); 2251 Configuration mPendingConfiguration = null; 2252 2253 // The lock of mProviderMap protects the following variables. 2254 final HashMap<String, ProviderRecord> mProviderMap 2255 = new HashMap<String, ProviderRecord>(); 2256 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap 2257 = new HashMap<IBinder, ProviderRefCount>(); 2258 final HashMap<IBinder, ProviderRecord> mLocalProviders 2259 = new HashMap<IBinder, ProviderRecord>(); 2260 2261 final GcIdler mGcIdler = new GcIdler(); 2262 boolean mGcIdlerScheduled = false; 2263 2264 public final PackageInfo getPackageInfo(String packageName, int flags) { 2265 synchronized (mPackages) { 2266 WeakReference<PackageInfo> ref; 2267 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) { 2268 ref = mPackages.get(packageName); 2269 } else { 2270 ref = mResourcePackages.get(packageName); 2271 } 2272 PackageInfo packageInfo = ref != null ? ref.get() : null; 2273 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo); 2274 if (packageInfo != null && (packageInfo.mResources == null 2275 || packageInfo.mResources.getAssets().isUpToDate())) { 2276 if (packageInfo.isSecurityViolation() 2277 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) { 2278 throw new SecurityException( 2279 "Requesting code from " + packageName 2280 + " to be run in process " 2281 + mBoundApplication.processName 2282 + "/" + mBoundApplication.appInfo.uid); 2283 } 2284 return packageInfo; 2285 } 2286 } 2287 2288 ApplicationInfo ai = null; 2289 try { 2290 ai = getPackageManager().getApplicationInfo(packageName, 2291 PackageManager.GET_SHARED_LIBRARY_FILES); 2292 } catch (RemoteException e) { 2293 } 2294 2295 if (ai != null) { 2296 return getPackageInfo(ai, flags); 2297 } 2298 2299 return null; 2300 } 2301 2302 public final PackageInfo getPackageInfo(ApplicationInfo ai, int flags) { 2303 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0; 2304 boolean securityViolation = includeCode && ai.uid != 0 2305 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null 2306 ? ai.uid != mBoundApplication.appInfo.uid : true); 2307 if ((flags&(Context.CONTEXT_INCLUDE_CODE 2308 |Context.CONTEXT_IGNORE_SECURITY)) 2309 == Context.CONTEXT_INCLUDE_CODE) { 2310 if (securityViolation) { 2311 String msg = "Requesting code from " + ai.packageName 2312 + " (with uid " + ai.uid + ")"; 2313 if (mBoundApplication != null) { 2314 msg = msg + " to be run in process " 2315 + mBoundApplication.processName + " (with uid " 2316 + mBoundApplication.appInfo.uid + ")"; 2317 } 2318 throw new SecurityException(msg); 2319 } 2320 } 2321 return getPackageInfo(ai, null, securityViolation, includeCode); 2322 } 2323 2324 public final PackageInfo getPackageInfoNoCheck(ApplicationInfo ai) { 2325 return getPackageInfo(ai, null, false, true); 2326 } 2327 2328 private final PackageInfo getPackageInfo(ApplicationInfo aInfo, 2329 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) { 2330 synchronized (mPackages) { 2331 WeakReference<PackageInfo> ref; 2332 if (includeCode) { 2333 ref = mPackages.get(aInfo.packageName); 2334 } else { 2335 ref = mResourcePackages.get(aInfo.packageName); 2336 } 2337 PackageInfo packageInfo = ref != null ? ref.get() : null; 2338 if (packageInfo == null || (packageInfo.mResources != null 2339 && !packageInfo.mResources.getAssets().isUpToDate())) { 2340 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package " 2341 : "Loading resource-only package ") + aInfo.packageName 2342 + " (in " + (mBoundApplication != null 2343 ? mBoundApplication.processName : null) 2344 + ")"); 2345 packageInfo = 2346 new PackageInfo(this, aInfo, this, baseLoader, 2347 securityViolation, includeCode && 2348 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0); 2349 if (includeCode) { 2350 mPackages.put(aInfo.packageName, 2351 new WeakReference<PackageInfo>(packageInfo)); 2352 } else { 2353 mResourcePackages.put(aInfo.packageName, 2354 new WeakReference<PackageInfo>(packageInfo)); 2355 } 2356 } 2357 return packageInfo; 2358 } 2359 } 2360 2361 public final boolean hasPackageInfo(String packageName) { 2362 synchronized (mPackages) { 2363 WeakReference<PackageInfo> ref; 2364 ref = mPackages.get(packageName); 2365 if (ref != null && ref.get() != null) { 2366 return true; 2367 } 2368 ref = mResourcePackages.get(packageName); 2369 if (ref != null && ref.get() != null) { 2370 return true; 2371 } 2372 return false; 2373 } 2374 } 2375 2376 ActivityThread() { 2377 } 2378 2379 public ApplicationThread getApplicationThread() 2380 { 2381 return mAppThread; 2382 } 2383 2384 public Instrumentation getInstrumentation() 2385 { 2386 return mInstrumentation; 2387 } 2388 2389 public Configuration getConfiguration() { 2390 return mConfiguration; 2391 } 2392 2393 public boolean isProfiling() { 2394 return mBoundApplication != null && mBoundApplication.profileFile != null; 2395 } 2396 2397 public String getProfileFilePath() { 2398 return mBoundApplication.profileFile; 2399 } 2400 2401 public Looper getLooper() { 2402 return mLooper; 2403 } 2404 2405 public Application getApplication() { 2406 return mInitialApplication; 2407 } 2408 2409 public String getProcessName() { 2410 return mBoundApplication.processName; 2411 } 2412 2413 public ContextImpl getSystemContext() { 2414 synchronized (this) { 2415 if (mSystemContext == null) { 2416 ContextImpl context = 2417 ContextImpl.createSystemContext(this); 2418 PackageInfo info = new PackageInfo(this, "android", context, null); 2419 context.init(info, null, this); 2420 context.getResources().updateConfiguration( 2421 getConfiguration(), getDisplayMetricsLocked(false)); 2422 mSystemContext = context; 2423 //Slog.i(TAG, "Created system resources " + context.getResources() 2424 // + ": " + context.getResources().getConfiguration()); 2425 } 2426 } 2427 return mSystemContext; 2428 } 2429 2430 public void installSystemApplicationInfo(ApplicationInfo info) { 2431 synchronized (this) { 2432 ContextImpl context = getSystemContext(); 2433 context.init(new PackageInfo(this, "android", context, info), null, this); 2434 } 2435 } 2436 2437 void ensureJitEnabled() { 2438 if (!mJitEnabled) { 2439 mJitEnabled = true; 2440 dalvik.system.VMRuntime.getRuntime().startJitCompilation(); 2441 } 2442 } 2443 2444 void scheduleGcIdler() { 2445 if (!mGcIdlerScheduled) { 2446 mGcIdlerScheduled = true; 2447 Looper.myQueue().addIdleHandler(mGcIdler); 2448 } 2449 mH.removeMessages(H.GC_WHEN_IDLE); 2450 } 2451 2452 void unscheduleGcIdler() { 2453 if (mGcIdlerScheduled) { 2454 mGcIdlerScheduled = false; 2455 Looper.myQueue().removeIdleHandler(mGcIdler); 2456 } 2457 mH.removeMessages(H.GC_WHEN_IDLE); 2458 } 2459 2460 void doGcIfNeeded() { 2461 mGcIdlerScheduled = false; 2462 final long now = SystemClock.uptimeMillis(); 2463 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime() 2464 // + "m now=" + now); 2465 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) { 2466 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!"); 2467 BinderInternal.forceGc("bg"); 2468 } 2469 } 2470 2471 public final ActivityInfo resolveActivityInfo(Intent intent) { 2472 ActivityInfo aInfo = intent.resolveActivityInfo( 2473 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES); 2474 if (aInfo == null) { 2475 // Throw an exception. 2476 Instrumentation.checkStartActivityResult( 2477 IActivityManager.START_CLASS_NOT_FOUND, intent); 2478 } 2479 return aInfo; 2480 } 2481 2482 public final Activity startActivityNow(Activity parent, String id, 2483 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state, 2484 Object lastNonConfigurationInstance) { 2485 ActivityRecord r = new ActivityRecord(); 2486 r.token = token; 2487 r.ident = 0; 2488 r.intent = intent; 2489 r.state = state; 2490 r.parent = parent; 2491 r.embeddedID = id; 2492 r.activityInfo = activityInfo; 2493 r.lastNonConfigurationInstance = lastNonConfigurationInstance; 2494 if (localLOGV) { 2495 ComponentName compname = intent.getComponent(); 2496 String name; 2497 if (compname != null) { 2498 name = compname.toShortString(); 2499 } else { 2500 name = "(Intent " + intent + ").getComponent() returned null"; 2501 } 2502 Slog.v(TAG, "Performing launch: action=" + intent.getAction() 2503 + ", comp=" + name 2504 + ", token=" + token); 2505 } 2506 return performLaunchActivity(r, null); 2507 } 2508 2509 public final Activity getActivity(IBinder token) { 2510 return mActivities.get(token).activity; 2511 } 2512 2513 public final void sendActivityResult( 2514 IBinder token, String id, int requestCode, 2515 int resultCode, Intent data) { 2516 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id 2517 + " req=" + requestCode + " res=" + resultCode + " data=" + data); 2518 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>(); 2519 list.add(new ResultInfo(id, requestCode, resultCode, data)); 2520 mAppThread.scheduleSendResult(token, list); 2521 } 2522 2523 // if the thread hasn't started yet, we don't have the handler, so just 2524 // save the messages until we're ready. 2525 private final void queueOrSendMessage(int what, Object obj) { 2526 queueOrSendMessage(what, obj, 0, 0); 2527 } 2528 2529 private final void queueOrSendMessage(int what, Object obj, int arg1) { 2530 queueOrSendMessage(what, obj, arg1, 0); 2531 } 2532 2533 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) { 2534 synchronized (this) { 2535 if (localLOGV) Slog.v( 2536 TAG, "SCHEDULE " + what + " " + mH.codeToString(what) 2537 + ": " + arg1 + " / " + obj); 2538 Message msg = Message.obtain(); 2539 msg.what = what; 2540 msg.obj = obj; 2541 msg.arg1 = arg1; 2542 msg.arg2 = arg2; 2543 mH.sendMessage(msg); 2544 } 2545 } 2546 2547 final void scheduleContextCleanup(ContextImpl context, String who, 2548 String what) { 2549 ContextCleanupInfo cci = new ContextCleanupInfo(); 2550 cci.context = context; 2551 cci.who = who; 2552 cci.what = what; 2553 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci); 2554 } 2555 2556 private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) { 2557 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")"); 2558 2559 ActivityInfo aInfo = r.activityInfo; 2560 if (r.packageInfo == null) { 2561 r.packageInfo = getPackageInfo(aInfo.applicationInfo, 2562 Context.CONTEXT_INCLUDE_CODE); 2563 } 2564 2565 ComponentName component = r.intent.getComponent(); 2566 if (component == null) { 2567 component = r.intent.resolveActivity( 2568 mInitialApplication.getPackageManager()); 2569 r.intent.setComponent(component); 2570 } 2571 2572 if (r.activityInfo.targetActivity != null) { 2573 component = new ComponentName(r.activityInfo.packageName, 2574 r.activityInfo.targetActivity); 2575 } 2576 2577 Activity activity = null; 2578 try { 2579 java.lang.ClassLoader cl = r.packageInfo.getClassLoader(); 2580 activity = mInstrumentation.newActivity( 2581 cl, component.getClassName(), r.intent); 2582 r.intent.setExtrasClassLoader(cl); 2583 if (r.state != null) { 2584 r.state.setClassLoader(cl); 2585 } 2586 } catch (Exception e) { 2587 if (!mInstrumentation.onException(activity, e)) { 2588 throw new RuntimeException( 2589 "Unable to instantiate activity " + component 2590 + ": " + e.toString(), e); 2591 } 2592 } 2593 2594 try { 2595 Application app = r.packageInfo.makeApplication(false, mInstrumentation); 2596 2597 if (localLOGV) Slog.v(TAG, "Performing launch of " + r); 2598 if (localLOGV) Slog.v( 2599 TAG, r + ": app=" + app 2600 + ", appName=" + app.getPackageName() 2601 + ", pkg=" + r.packageInfo.getPackageName() 2602 + ", comp=" + r.intent.getComponent().toShortString() 2603 + ", dir=" + r.packageInfo.getAppDir()); 2604 2605 if (activity != null) { 2606 ContextImpl appContext = new ContextImpl(); 2607 appContext.init(r.packageInfo, r.token, this); 2608 appContext.setOuterContext(activity); 2609 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); 2610 Configuration config = new Configuration(mConfiguration); 2611 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity " 2612 + r.activityInfo.name + " with config " + config); 2613 activity.attach(appContext, this, getInstrumentation(), r.token, 2614 r.ident, app, r.intent, r.activityInfo, title, r.parent, 2615 r.embeddedID, r.lastNonConfigurationInstance, 2616 r.lastNonConfigurationChildInstances, config); 2617 2618 if (customIntent != null) { 2619 activity.mIntent = customIntent; 2620 } 2621 r.lastNonConfigurationInstance = null; 2622 r.lastNonConfigurationChildInstances = null; 2623 activity.mStartedActivity = false; 2624 int theme = r.activityInfo.getThemeResource(); 2625 if (theme != 0) { 2626 activity.setTheme(theme); 2627 } 2628 2629 activity.mCalled = false; 2630 mInstrumentation.callActivityOnCreate(activity, r.state); 2631 if (!activity.mCalled) { 2632 throw new SuperNotCalledException( 2633 "Activity " + r.intent.getComponent().toShortString() + 2634 " did not call through to super.onCreate()"); 2635 } 2636 r.activity = activity; 2637 r.stopped = true; 2638 if (!r.activity.mFinished) { 2639 activity.performStart(); 2640 r.stopped = false; 2641 } 2642 if (!r.activity.mFinished) { 2643 if (r.state != null) { 2644 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state); 2645 } 2646 } 2647 if (!r.activity.mFinished) { 2648 activity.mCalled = false; 2649 mInstrumentation.callActivityOnPostCreate(activity, r.state); 2650 if (!activity.mCalled) { 2651 throw new SuperNotCalledException( 2652 "Activity " + r.intent.getComponent().toShortString() + 2653 " did not call through to super.onPostCreate()"); 2654 } 2655 } 2656 } 2657 r.paused = true; 2658 2659 mActivities.put(r.token, r); 2660 2661 } catch (SuperNotCalledException e) { 2662 throw e; 2663 2664 } catch (Exception e) { 2665 if (!mInstrumentation.onException(activity, e)) { 2666 throw new RuntimeException( 2667 "Unable to start activity " + component 2668 + ": " + e.toString(), e); 2669 } 2670 } 2671 2672 return activity; 2673 } 2674 2675 private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) { 2676 // If we are getting ready to gc after going to the background, well 2677 // we are back active so skip it. 2678 unscheduleGcIdler(); 2679 2680 if (localLOGV) Slog.v( 2681 TAG, "Handling launch of " + r); 2682 Activity a = performLaunchActivity(r, customIntent); 2683 2684 if (a != null) { 2685 r.createdConfig = new Configuration(mConfiguration); 2686 Bundle oldState = r.state; 2687 handleResumeActivity(r.token, false, r.isForward); 2688 2689 if (!r.activity.mFinished && r.startsNotResumed) { 2690 // The activity manager actually wants this one to start out 2691 // paused, because it needs to be visible but isn't in the 2692 // foreground. We accomplish this by going through the 2693 // normal startup (because activities expect to go through 2694 // onResume() the first time they run, before their window 2695 // is displayed), and then pausing it. However, in this case 2696 // we do -not- need to do the full pause cycle (of freezing 2697 // and such) because the activity manager assumes it can just 2698 // retain the current state it has. 2699 try { 2700 r.activity.mCalled = false; 2701 mInstrumentation.callActivityOnPause(r.activity); 2702 // We need to keep around the original state, in case 2703 // we need to be created again. 2704 r.state = oldState; 2705 if (!r.activity.mCalled) { 2706 throw new SuperNotCalledException( 2707 "Activity " + r.intent.getComponent().toShortString() + 2708 " did not call through to super.onPause()"); 2709 } 2710 2711 } catch (SuperNotCalledException e) { 2712 throw e; 2713 2714 } catch (Exception e) { 2715 if (!mInstrumentation.onException(r.activity, e)) { 2716 throw new RuntimeException( 2717 "Unable to pause activity " 2718 + r.intent.getComponent().toShortString() 2719 + ": " + e.toString(), e); 2720 } 2721 } 2722 r.paused = true; 2723 } 2724 } else { 2725 // If there was an error, for any reason, tell the activity 2726 // manager to stop us. 2727 try { 2728 ActivityManagerNative.getDefault() 2729 .finishActivity(r.token, Activity.RESULT_CANCELED, null); 2730 } catch (RemoteException ex) { 2731 } 2732 } 2733 } 2734 2735 private final void deliverNewIntents(ActivityRecord r, 2736 List<Intent> intents) { 2737 final int N = intents.size(); 2738 for (int i=0; i<N; i++) { 2739 Intent intent = intents.get(i); 2740 intent.setExtrasClassLoader(r.activity.getClassLoader()); 2741 mInstrumentation.callActivityOnNewIntent(r.activity, intent); 2742 } 2743 } 2744 2745 public final void performNewIntents(IBinder token, 2746 List<Intent> intents) { 2747 ActivityRecord r = mActivities.get(token); 2748 if (r != null) { 2749 final boolean resumed = !r.paused; 2750 if (resumed) { 2751 mInstrumentation.callActivityOnPause(r.activity); 2752 } 2753 deliverNewIntents(r, intents); 2754 if (resumed) { 2755 mInstrumentation.callActivityOnResume(r.activity); 2756 } 2757 } 2758 } 2759 2760 private final void handleNewIntent(NewIntentData data) { 2761 performNewIntents(data.token, data.intents); 2762 } 2763 2764 private final void handleReceiver(ReceiverData data) { 2765 // If we are getting ready to gc after going to the background, well 2766 // we are back active so skip it. 2767 unscheduleGcIdler(); 2768 2769 String component = data.intent.getComponent().getClassName(); 2770 2771 PackageInfo packageInfo = getPackageInfoNoCheck( 2772 data.info.applicationInfo); 2773 2774 IActivityManager mgr = ActivityManagerNative.getDefault(); 2775 2776 BroadcastReceiver receiver = null; 2777 try { 2778 java.lang.ClassLoader cl = packageInfo.getClassLoader(); 2779 data.intent.setExtrasClassLoader(cl); 2780 if (data.resultExtras != null) { 2781 data.resultExtras.setClassLoader(cl); 2782 } 2783 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance(); 2784 } catch (Exception e) { 2785 try { 2786 if (DEBUG_BROADCAST) Slog.i(TAG, 2787 "Finishing failed broadcast to " + data.intent.getComponent()); 2788 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode, 2789 data.resultData, data.resultExtras, data.resultAbort); 2790 } catch (RemoteException ex) { 2791 } 2792 throw new RuntimeException( 2793 "Unable to instantiate receiver " + component 2794 + ": " + e.toString(), e); 2795 } 2796 2797 try { 2798 Application app = packageInfo.makeApplication(false, mInstrumentation); 2799 2800 if (localLOGV) Slog.v( 2801 TAG, "Performing receive of " + data.intent 2802 + ": app=" + app 2803 + ", appName=" + app.getPackageName() 2804 + ", pkg=" + packageInfo.getPackageName() 2805 + ", comp=" + data.intent.getComponent().toShortString() 2806 + ", dir=" + packageInfo.getAppDir()); 2807 2808 ContextImpl context = (ContextImpl)app.getBaseContext(); 2809 receiver.setOrderedHint(true); 2810 receiver.setResult(data.resultCode, data.resultData, 2811 data.resultExtras); 2812 receiver.setOrderedHint(data.sync); 2813 receiver.onReceive(context.getReceiverRestrictedContext(), 2814 data.intent); 2815 } catch (Exception e) { 2816 try { 2817 if (DEBUG_BROADCAST) Slog.i(TAG, 2818 "Finishing failed broadcast to " + data.intent.getComponent()); 2819 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode, 2820 data.resultData, data.resultExtras, data.resultAbort); 2821 } catch (RemoteException ex) { 2822 } 2823 if (!mInstrumentation.onException(receiver, e)) { 2824 throw new RuntimeException( 2825 "Unable to start receiver " + component 2826 + ": " + e.toString(), e); 2827 } 2828 } 2829 2830 try { 2831 if (data.sync) { 2832 if (DEBUG_BROADCAST) Slog.i(TAG, 2833 "Finishing ordered broadcast to " + data.intent.getComponent()); 2834 mgr.finishReceiver( 2835 mAppThread.asBinder(), receiver.getResultCode(), 2836 receiver.getResultData(), receiver.getResultExtras(false), 2837 receiver.getAbortBroadcast()); 2838 } else { 2839 if (DEBUG_BROADCAST) Slog.i(TAG, 2840 "Finishing broadcast to " + data.intent.getComponent()); 2841 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false); 2842 } 2843 } catch (RemoteException ex) { 2844 } 2845 } 2846 2847 // Instantiate a BackupAgent and tell it that it's alive 2848 private final void handleCreateBackupAgent(CreateBackupAgentData data) { 2849 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data); 2850 2851 // no longer idle; we have backup work to do 2852 unscheduleGcIdler(); 2853 2854 // instantiate the BackupAgent class named in the manifest 2855 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo); 2856 String packageName = packageInfo.mPackageName; 2857 if (mBackupAgents.get(packageName) != null) { 2858 Slog.d(TAG, "BackupAgent " + " for " + packageName 2859 + " already exists"); 2860 return; 2861 } 2862 2863 BackupAgent agent = null; 2864 String classname = data.appInfo.backupAgentName; 2865 if (classname == null) { 2866 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) { 2867 Slog.e(TAG, "Attempted incremental backup but no defined agent for " 2868 + packageName); 2869 return; 2870 } 2871 classname = "android.app.FullBackupAgent"; 2872 } 2873 try { 2874 IBinder binder = null; 2875 try { 2876 java.lang.ClassLoader cl = packageInfo.getClassLoader(); 2877 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance(); 2878 2879 // set up the agent's context 2880 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent " 2881 + data.appInfo.backupAgentName); 2882 2883 ContextImpl context = new ContextImpl(); 2884 context.init(packageInfo, null, this); 2885 context.setOuterContext(agent); 2886 agent.attach(context); 2887 2888 agent.onCreate(); 2889 binder = agent.onBind(); 2890 mBackupAgents.put(packageName, agent); 2891 } catch (Exception e) { 2892 // If this is during restore, fail silently; otherwise go 2893 // ahead and let the user see the crash. 2894 Slog.e(TAG, "Agent threw during creation: " + e); 2895 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) { 2896 throw e; 2897 } 2898 // falling through with 'binder' still null 2899 } 2900 2901 // tell the OS that we're live now 2902 try { 2903 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder); 2904 } catch (RemoteException e) { 2905 // nothing to do. 2906 } 2907 } catch (Exception e) { 2908 throw new RuntimeException("Unable to create BackupAgent " 2909 + data.appInfo.backupAgentName + ": " + e.toString(), e); 2910 } 2911 } 2912 2913 // Tear down a BackupAgent 2914 private final void handleDestroyBackupAgent(CreateBackupAgentData data) { 2915 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data); 2916 2917 PackageInfo packageInfo = getPackageInfoNoCheck(data.appInfo); 2918 String packageName = packageInfo.mPackageName; 2919 BackupAgent agent = mBackupAgents.get(packageName); 2920 if (agent != null) { 2921 try { 2922 agent.onDestroy(); 2923 } catch (Exception e) { 2924 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo); 2925 e.printStackTrace(); 2926 } 2927 mBackupAgents.remove(packageName); 2928 } else { 2929 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data); 2930 } 2931 } 2932 2933 private final void handleCreateService(CreateServiceData data) { 2934 // If we are getting ready to gc after going to the background, well 2935 // we are back active so skip it. 2936 unscheduleGcIdler(); 2937 2938 PackageInfo packageInfo = getPackageInfoNoCheck( 2939 data.info.applicationInfo); 2940 Service service = null; 2941 try { 2942 java.lang.ClassLoader cl = packageInfo.getClassLoader(); 2943 service = (Service) cl.loadClass(data.info.name).newInstance(); 2944 } catch (Exception e) { 2945 if (!mInstrumentation.onException(service, e)) { 2946 throw new RuntimeException( 2947 "Unable to instantiate service " + data.info.name 2948 + ": " + e.toString(), e); 2949 } 2950 } 2951 2952 try { 2953 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name); 2954 2955 ContextImpl context = new ContextImpl(); 2956 context.init(packageInfo, null, this); 2957 2958 Application app = packageInfo.makeApplication(false, mInstrumentation); 2959 context.setOuterContext(service); 2960 service.attach(context, this, data.info.name, data.token, app, 2961 ActivityManagerNative.getDefault()); 2962 service.onCreate(); 2963 mServices.put(data.token, service); 2964 try { 2965 ActivityManagerNative.getDefault().serviceDoneExecuting( 2966 data.token, 0, 0, 0); 2967 } catch (RemoteException e) { 2968 // nothing to do. 2969 } 2970 } catch (Exception e) { 2971 if (!mInstrumentation.onException(service, e)) { 2972 throw new RuntimeException( 2973 "Unable to create service " + data.info.name 2974 + ": " + e.toString(), e); 2975 } 2976 } 2977 } 2978 2979 private final void handleBindService(BindServiceData data) { 2980 Service s = mServices.get(data.token); 2981 if (s != null) { 2982 try { 2983 data.intent.setExtrasClassLoader(s.getClassLoader()); 2984 try { 2985 if (!data.rebind) { 2986 IBinder binder = s.onBind(data.intent); 2987 ActivityManagerNative.getDefault().publishService( 2988 data.token, data.intent, binder); 2989 } else { 2990 s.onRebind(data.intent); 2991 ActivityManagerNative.getDefault().serviceDoneExecuting( 2992 data.token, 0, 0, 0); 2993 } 2994 ensureJitEnabled(); 2995 } catch (RemoteException ex) { 2996 } 2997 } catch (Exception e) { 2998 if (!mInstrumentation.onException(s, e)) { 2999 throw new RuntimeException( 3000 "Unable to bind to service " + s 3001 + " with " + data.intent + ": " + e.toString(), e); 3002 } 3003 } 3004 } 3005 } 3006 3007 private final void handleUnbindService(BindServiceData data) { 3008 Service s = mServices.get(data.token); 3009 if (s != null) { 3010 try { 3011 data.intent.setExtrasClassLoader(s.getClassLoader()); 3012 boolean doRebind = s.onUnbind(data.intent); 3013 try { 3014 if (doRebind) { 3015 ActivityManagerNative.getDefault().unbindFinished( 3016 data.token, data.intent, doRebind); 3017 } else { 3018 ActivityManagerNative.getDefault().serviceDoneExecuting( 3019 data.token, 0, 0, 0); 3020 } 3021 } catch (RemoteException ex) { 3022 } 3023 } catch (Exception e) { 3024 if (!mInstrumentation.onException(s, e)) { 3025 throw new RuntimeException( 3026 "Unable to unbind to service " + s 3027 + " with " + data.intent + ": " + e.toString(), e); 3028 } 3029 } 3030 } 3031 } 3032 3033 private void handleDumpService(DumpServiceInfo info) { 3034 try { 3035 Service s = mServices.get(info.service); 3036 if (s != null) { 3037 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd)); 3038 s.dump(info.fd, pw, info.args); 3039 pw.close(); 3040 } 3041 } finally { 3042 synchronized (info) { 3043 info.dumped = true; 3044 info.notifyAll(); 3045 } 3046 } 3047 } 3048 3049 private final void handleServiceArgs(ServiceArgsData data) { 3050 Service s = mServices.get(data.token); 3051 if (s != null) { 3052 try { 3053 if (data.args != null) { 3054 data.args.setExtrasClassLoader(s.getClassLoader()); 3055 } 3056 int res = s.onStartCommand(data.args, data.flags, data.startId); 3057 try { 3058 ActivityManagerNative.getDefault().serviceDoneExecuting( 3059 data.token, 1, data.startId, res); 3060 } catch (RemoteException e) { 3061 // nothing to do. 3062 } 3063 ensureJitEnabled(); 3064 } catch (Exception e) { 3065 if (!mInstrumentation.onException(s, e)) { 3066 throw new RuntimeException( 3067 "Unable to start service " + s 3068 + " with " + data.args + ": " + e.toString(), e); 3069 } 3070 } 3071 } 3072 } 3073 3074 private final void handleStopService(IBinder token) { 3075 Service s = mServices.remove(token); 3076 if (s != null) { 3077 try { 3078 if (localLOGV) Slog.v(TAG, "Destroying service " + s); 3079 s.onDestroy(); 3080 Context context = s.getBaseContext(); 3081 if (context instanceof ContextImpl) { 3082 final String who = s.getClassName(); 3083 ((ContextImpl) context).scheduleFinalCleanup(who, "Service"); 3084 } 3085 try { 3086 ActivityManagerNative.getDefault().serviceDoneExecuting( 3087 token, 0, 0, 0); 3088 } catch (RemoteException e) { 3089 // nothing to do. 3090 } 3091 } catch (Exception e) { 3092 if (!mInstrumentation.onException(s, e)) { 3093 throw new RuntimeException( 3094 "Unable to stop service " + s 3095 + ": " + e.toString(), e); 3096 } 3097 } 3098 } 3099 //Slog.i(TAG, "Running services: " + mServices); 3100 } 3101 3102 public final ActivityRecord performResumeActivity(IBinder token, 3103 boolean clearHide) { 3104 ActivityRecord r = mActivities.get(token); 3105 if (localLOGV) Slog.v(TAG, "Performing resume of " + r 3106 + " finished=" + r.activity.mFinished); 3107 if (r != null && !r.activity.mFinished) { 3108 if (clearHide) { 3109 r.hideForNow = false; 3110 r.activity.mStartedActivity = false; 3111 } 3112 try { 3113 if (r.pendingIntents != null) { 3114 deliverNewIntents(r, r.pendingIntents); 3115 r.pendingIntents = null; 3116 } 3117 if (r.pendingResults != null) { 3118 deliverResults(r, r.pendingResults); 3119 r.pendingResults = null; 3120 } 3121 r.activity.performResume(); 3122 3123 EventLog.writeEvent(LOG_ON_RESUME_CALLED, 3124 r.activity.getComponentName().getClassName()); 3125 3126 r.paused = false; 3127 r.stopped = false; 3128 r.state = null; 3129 } catch (Exception e) { 3130 if (!mInstrumentation.onException(r.activity, e)) { 3131 throw new RuntimeException( 3132 "Unable to resume activity " 3133 + r.intent.getComponent().toShortString() 3134 + ": " + e.toString(), e); 3135 } 3136 } 3137 } 3138 return r; 3139 } 3140 3141 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) { 3142 // If we are getting ready to gc after going to the background, well 3143 // we are back active so skip it. 3144 unscheduleGcIdler(); 3145 3146 ActivityRecord r = performResumeActivity(token, clearHide); 3147 3148 if (r != null) { 3149 final Activity a = r.activity; 3150 3151 if (localLOGV) Slog.v( 3152 TAG, "Resume " + r + " started activity: " + 3153 a.mStartedActivity + ", hideForNow: " + r.hideForNow 3154 + ", finished: " + a.mFinished); 3155 3156 final int forwardBit = isForward ? 3157 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0; 3158 3159 // If the window hasn't yet been added to the window manager, 3160 // and this guy didn't finish itself or start another activity, 3161 // then go ahead and add the window. 3162 boolean willBeVisible = !a.mStartedActivity; 3163 if (!willBeVisible) { 3164 try { 3165 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible( 3166 a.getActivityToken()); 3167 } catch (RemoteException e) { 3168 } 3169 } 3170 if (r.window == null && !a.mFinished && willBeVisible) { 3171 r.window = r.activity.getWindow(); 3172 View decor = r.window.getDecorView(); 3173 decor.setVisibility(View.INVISIBLE); 3174 ViewManager wm = a.getWindowManager(); 3175 WindowManager.LayoutParams l = r.window.getAttributes(); 3176 a.mDecor = decor; 3177 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION; 3178 l.softInputMode |= forwardBit; 3179 if (a.mVisibleFromClient) { 3180 a.mWindowAdded = true; 3181 wm.addView(decor, l); 3182 } 3183 3184 // If the window has already been added, but during resume 3185 // we started another activity, then don't yet make the 3186 // window visible. 3187 } else if (!willBeVisible) { 3188 if (localLOGV) Slog.v( 3189 TAG, "Launch " + r + " mStartedActivity set"); 3190 r.hideForNow = true; 3191 } 3192 3193 // The window is now visible if it has been added, we are not 3194 // simply finishing, and we are not starting another activity. 3195 if (!r.activity.mFinished && willBeVisible 3196 && r.activity.mDecor != null && !r.hideForNow) { 3197 if (r.newConfig != null) { 3198 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity " 3199 + r.activityInfo.name + " with newConfig " + r.newConfig); 3200 performConfigurationChanged(r.activity, r.newConfig); 3201 r.newConfig = null; 3202 } 3203 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" 3204 + isForward); 3205 WindowManager.LayoutParams l = r.window.getAttributes(); 3206 if ((l.softInputMode 3207 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) 3208 != forwardBit) { 3209 l.softInputMode = (l.softInputMode 3210 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)) 3211 | forwardBit; 3212 if (r.activity.mVisibleFromClient) { 3213 ViewManager wm = a.getWindowManager(); 3214 View decor = r.window.getDecorView(); 3215 wm.updateViewLayout(decor, l); 3216 } 3217 } 3218 r.activity.mVisibleFromServer = true; 3219 mNumVisibleActivities++; 3220 if (r.activity.mVisibleFromClient) { 3221 r.activity.makeVisible(); 3222 } 3223 } 3224 3225 r.nextIdle = mNewActivities; 3226 mNewActivities = r; 3227 if (localLOGV) Slog.v( 3228 TAG, "Scheduling idle handler for " + r); 3229 Looper.myQueue().addIdleHandler(new Idler()); 3230 3231 } else { 3232 // If an exception was thrown when trying to resume, then 3233 // just end this activity. 3234 try { 3235 ActivityManagerNative.getDefault() 3236 .finishActivity(token, Activity.RESULT_CANCELED, null); 3237 } catch (RemoteException ex) { 3238 } 3239 } 3240 } 3241 3242 private int mThumbnailWidth = -1; 3243 private int mThumbnailHeight = -1; 3244 3245 private final Bitmap createThumbnailBitmap(ActivityRecord r) { 3246 Bitmap thumbnail = null; 3247 try { 3248 int w = mThumbnailWidth; 3249 int h; 3250 if (w < 0) { 3251 Resources res = r.activity.getResources(); 3252 mThumbnailHeight = h = 3253 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height); 3254 3255 mThumbnailWidth = w = 3256 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width); 3257 } else { 3258 h = mThumbnailHeight; 3259 } 3260 3261 // XXX Only set hasAlpha if needed? 3262 thumbnail = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565); 3263 thumbnail.eraseColor(0); 3264 Canvas cv = new Canvas(thumbnail); 3265 if (!r.activity.onCreateThumbnail(thumbnail, cv)) { 3266 thumbnail = null; 3267 } 3268 } catch (Exception e) { 3269 if (!mInstrumentation.onException(r.activity, e)) { 3270 throw new RuntimeException( 3271 "Unable to create thumbnail of " 3272 + r.intent.getComponent().toShortString() 3273 + ": " + e.toString(), e); 3274 } 3275 thumbnail = null; 3276 } 3277 3278 return thumbnail; 3279 } 3280 3281 private final void handlePauseActivity(IBinder token, boolean finished, 3282 boolean userLeaving, int configChanges) { 3283 ActivityRecord r = mActivities.get(token); 3284 if (r != null) { 3285 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r); 3286 if (userLeaving) { 3287 performUserLeavingActivity(r); 3288 } 3289 3290 r.activity.mConfigChangeFlags |= configChanges; 3291 Bundle state = performPauseActivity(token, finished, true); 3292 3293 // Tell the activity manager we have paused. 3294 try { 3295 ActivityManagerNative.getDefault().activityPaused(token, state); 3296 } catch (RemoteException ex) { 3297 } 3298 } 3299 } 3300 3301 final void performUserLeavingActivity(ActivityRecord r) { 3302 mInstrumentation.callActivityOnUserLeaving(r.activity); 3303 } 3304 3305 final Bundle performPauseActivity(IBinder token, boolean finished, 3306 boolean saveState) { 3307 ActivityRecord r = mActivities.get(token); 3308 return r != null ? performPauseActivity(r, finished, saveState) : null; 3309 } 3310 3311 final Bundle performPauseActivity(ActivityRecord r, boolean finished, 3312 boolean saveState) { 3313 if (r.paused) { 3314 if (r.activity.mFinished) { 3315 // If we are finishing, we won't call onResume() in certain cases. 3316 // So here we likewise don't want to call onPause() if the activity 3317 // isn't resumed. 3318 return null; 3319 } 3320 RuntimeException e = new RuntimeException( 3321 "Performing pause of activity that is not resumed: " 3322 + r.intent.getComponent().toShortString()); 3323 Slog.e(TAG, e.getMessage(), e); 3324 } 3325 Bundle state = null; 3326 if (finished) { 3327 r.activity.mFinished = true; 3328 } 3329 try { 3330 // Next have the activity save its current state and managed dialogs... 3331 if (!r.activity.mFinished && saveState) { 3332 state = new Bundle(); 3333 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state); 3334 r.state = state; 3335 } 3336 // Now we are idle. 3337 r.activity.mCalled = false; 3338 mInstrumentation.callActivityOnPause(r.activity); 3339 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName()); 3340 if (!r.activity.mCalled) { 3341 throw new SuperNotCalledException( 3342 "Activity " + r.intent.getComponent().toShortString() + 3343 " did not call through to super.onPause()"); 3344 } 3345 3346 } catch (SuperNotCalledException e) { 3347 throw e; 3348 3349 } catch (Exception e) { 3350 if (!mInstrumentation.onException(r.activity, e)) { 3351 throw new RuntimeException( 3352 "Unable to pause activity " 3353 + r.intent.getComponent().toShortString() 3354 + ": " + e.toString(), e); 3355 } 3356 } 3357 r.paused = true; 3358 return state; 3359 } 3360 3361 final void performStopActivity(IBinder token) { 3362 ActivityRecord r = mActivities.get(token); 3363 performStopActivityInner(r, null, false); 3364 } 3365 3366 private static class StopInfo { 3367 Bitmap thumbnail; 3368 CharSequence description; 3369 } 3370 3371 private final class ProviderRefCount { 3372 public int count; 3373 ProviderRefCount(int pCount) { 3374 count = pCount; 3375 } 3376 } 3377 3378 private final void performStopActivityInner(ActivityRecord r, 3379 StopInfo info, boolean keepShown) { 3380 if (localLOGV) Slog.v(TAG, "Performing stop of " + r); 3381 if (r != null) { 3382 if (!keepShown && r.stopped) { 3383 if (r.activity.mFinished) { 3384 // If we are finishing, we won't call onResume() in certain 3385 // cases. So here we likewise don't want to call onStop() 3386 // if the activity isn't resumed. 3387 return; 3388 } 3389 RuntimeException e = new RuntimeException( 3390 "Performing stop of activity that is not resumed: " 3391 + r.intent.getComponent().toShortString()); 3392 Slog.e(TAG, e.getMessage(), e); 3393 } 3394 3395 if (info != null) { 3396 try { 3397 // First create a thumbnail for the activity... 3398 //info.thumbnail = createThumbnailBitmap(r); 3399 info.description = r.activity.onCreateDescription(); 3400 } catch (Exception e) { 3401 if (!mInstrumentation.onException(r.activity, e)) { 3402 throw new RuntimeException( 3403 "Unable to save state of activity " 3404 + r.intent.getComponent().toShortString() 3405 + ": " + e.toString(), e); 3406 } 3407 } 3408 } 3409 3410 if (!keepShown) { 3411 try { 3412 // Now we are idle. 3413 r.activity.performStop(); 3414 } catch (Exception e) { 3415 if (!mInstrumentation.onException(r.activity, e)) { 3416 throw new RuntimeException( 3417 "Unable to stop activity " 3418 + r.intent.getComponent().toShortString() 3419 + ": " + e.toString(), e); 3420 } 3421 } 3422 r.stopped = true; 3423 } 3424 3425 r.paused = true; 3426 } 3427 } 3428 3429 private final void updateVisibility(ActivityRecord r, boolean show) { 3430 View v = r.activity.mDecor; 3431 if (v != null) { 3432 if (show) { 3433 if (!r.activity.mVisibleFromServer) { 3434 r.activity.mVisibleFromServer = true; 3435 mNumVisibleActivities++; 3436 if (r.activity.mVisibleFromClient) { 3437 r.activity.makeVisible(); 3438 } 3439 } 3440 if (r.newConfig != null) { 3441 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis " 3442 + r.activityInfo.name + " with new config " + r.newConfig); 3443 performConfigurationChanged(r.activity, r.newConfig); 3444 r.newConfig = null; 3445 } 3446 } else { 3447 if (r.activity.mVisibleFromServer) { 3448 r.activity.mVisibleFromServer = false; 3449 mNumVisibleActivities--; 3450 v.setVisibility(View.INVISIBLE); 3451 } 3452 } 3453 } 3454 } 3455 3456 private final void handleStopActivity(IBinder token, boolean show, int configChanges) { 3457 ActivityRecord r = mActivities.get(token); 3458 r.activity.mConfigChangeFlags |= configChanges; 3459 3460 StopInfo info = new StopInfo(); 3461 performStopActivityInner(r, info, show); 3462 3463 if (localLOGV) Slog.v( 3464 TAG, "Finishing stop of " + r + ": show=" + show 3465 + " win=" + r.window); 3466 3467 updateVisibility(r, show); 3468 3469 // Tell activity manager we have been stopped. 3470 try { 3471 ActivityManagerNative.getDefault().activityStopped( 3472 r.token, info.thumbnail, info.description); 3473 } catch (RemoteException ex) { 3474 } 3475 } 3476 3477 final void performRestartActivity(IBinder token) { 3478 ActivityRecord r = mActivities.get(token); 3479 if (r.stopped) { 3480 r.activity.performRestart(); 3481 r.stopped = false; 3482 } 3483 } 3484 3485 private final void handleWindowVisibility(IBinder token, boolean show) { 3486 ActivityRecord r = mActivities.get(token); 3487 if (!show && !r.stopped) { 3488 performStopActivityInner(r, null, show); 3489 } else if (show && r.stopped) { 3490 // If we are getting ready to gc after going to the background, well 3491 // we are back active so skip it. 3492 unscheduleGcIdler(); 3493 3494 r.activity.performRestart(); 3495 r.stopped = false; 3496 } 3497 if (r.activity.mDecor != null) { 3498 if (Config.LOGV) Slog.v( 3499 TAG, "Handle window " + r + " visibility: " + show); 3500 updateVisibility(r, show); 3501 } 3502 } 3503 3504 private final void deliverResults(ActivityRecord r, List<ResultInfo> results) { 3505 final int N = results.size(); 3506 for (int i=0; i<N; i++) { 3507 ResultInfo ri = results.get(i); 3508 try { 3509 if (ri.mData != null) { 3510 ri.mData.setExtrasClassLoader(r.activity.getClassLoader()); 3511 } 3512 if (DEBUG_RESULTS) Slog.v(TAG, 3513 "Delivering result to activity " + r + " : " + ri); 3514 r.activity.dispatchActivityResult(ri.mResultWho, 3515 ri.mRequestCode, ri.mResultCode, ri.mData); 3516 } catch (Exception e) { 3517 if (!mInstrumentation.onException(r.activity, e)) { 3518 throw new RuntimeException( 3519 "Failure delivering result " + ri + " to activity " 3520 + r.intent.getComponent().toShortString() 3521 + ": " + e.toString(), e); 3522 } 3523 } 3524 } 3525 } 3526 3527 private final void handleSendResult(ResultData res) { 3528 ActivityRecord r = mActivities.get(res.token); 3529 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r); 3530 if (r != null) { 3531 final boolean resumed = !r.paused; 3532 if (!r.activity.mFinished && r.activity.mDecor != null 3533 && r.hideForNow && resumed) { 3534 // We had hidden the activity because it started another 3535 // one... we have gotten a result back and we are not 3536 // paused, so make sure our window is visible. 3537 updateVisibility(r, true); 3538 } 3539 if (resumed) { 3540 try { 3541 // Now we are idle. 3542 r.activity.mCalled = false; 3543 mInstrumentation.callActivityOnPause(r.activity); 3544 if (!r.activity.mCalled) { 3545 throw new SuperNotCalledException( 3546 "Activity " + r.intent.getComponent().toShortString() 3547 + " did not call through to super.onPause()"); 3548 } 3549 } catch (SuperNotCalledException e) { 3550 throw e; 3551 } catch (Exception e) { 3552 if (!mInstrumentation.onException(r.activity, e)) { 3553 throw new RuntimeException( 3554 "Unable to pause activity " 3555 + r.intent.getComponent().toShortString() 3556 + ": " + e.toString(), e); 3557 } 3558 } 3559 } 3560 deliverResults(r, res.results); 3561 if (resumed) { 3562 mInstrumentation.callActivityOnResume(r.activity); 3563 } 3564 } 3565 } 3566 3567 public final ActivityRecord performDestroyActivity(IBinder token, boolean finishing) { 3568 return performDestroyActivity(token, finishing, 0, false); 3569 } 3570 3571 private final ActivityRecord performDestroyActivity(IBinder token, boolean finishing, 3572 int configChanges, boolean getNonConfigInstance) { 3573 ActivityRecord r = mActivities.get(token); 3574 if (localLOGV) Slog.v(TAG, "Performing finish of " + r); 3575 if (r != null) { 3576 r.activity.mConfigChangeFlags |= configChanges; 3577 if (finishing) { 3578 r.activity.mFinished = true; 3579 } 3580 if (!r.paused) { 3581 try { 3582 r.activity.mCalled = false; 3583 mInstrumentation.callActivityOnPause(r.activity); 3584 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, 3585 r.activity.getComponentName().getClassName()); 3586 if (!r.activity.mCalled) { 3587 throw new SuperNotCalledException( 3588 "Activity " + safeToComponentShortString(r.intent) 3589 + " did not call through to super.onPause()"); 3590 } 3591 } catch (SuperNotCalledException e) { 3592 throw e; 3593 } catch (Exception e) { 3594 if (!mInstrumentation.onException(r.activity, e)) { 3595 throw new RuntimeException( 3596 "Unable to pause activity " 3597 + safeToComponentShortString(r.intent) 3598 + ": " + e.toString(), e); 3599 } 3600 } 3601 r.paused = true; 3602 } 3603 if (!r.stopped) { 3604 try { 3605 r.activity.performStop(); 3606 } catch (SuperNotCalledException e) { 3607 throw e; 3608 } catch (Exception e) { 3609 if (!mInstrumentation.onException(r.activity, e)) { 3610 throw new RuntimeException( 3611 "Unable to stop activity " 3612 + safeToComponentShortString(r.intent) 3613 + ": " + e.toString(), e); 3614 } 3615 } 3616 r.stopped = true; 3617 } 3618 if (getNonConfigInstance) { 3619 try { 3620 r.lastNonConfigurationInstance 3621 = r.activity.onRetainNonConfigurationInstance(); 3622 } catch (Exception e) { 3623 if (!mInstrumentation.onException(r.activity, e)) { 3624 throw new RuntimeException( 3625 "Unable to retain activity " 3626 + r.intent.getComponent().toShortString() 3627 + ": " + e.toString(), e); 3628 } 3629 } 3630 try { 3631 r.lastNonConfigurationChildInstances 3632 = r.activity.onRetainNonConfigurationChildInstances(); 3633 } catch (Exception e) { 3634 if (!mInstrumentation.onException(r.activity, e)) { 3635 throw new RuntimeException( 3636 "Unable to retain child activities " 3637 + safeToComponentShortString(r.intent) 3638 + ": " + e.toString(), e); 3639 } 3640 } 3641 3642 } 3643 try { 3644 r.activity.mCalled = false; 3645 r.activity.onDestroy(); 3646 if (!r.activity.mCalled) { 3647 throw new SuperNotCalledException( 3648 "Activity " + safeToComponentShortString(r.intent) + 3649 " did not call through to super.onDestroy()"); 3650 } 3651 if (r.window != null) { 3652 r.window.closeAllPanels(); 3653 } 3654 } catch (SuperNotCalledException e) { 3655 throw e; 3656 } catch (Exception e) { 3657 if (!mInstrumentation.onException(r.activity, e)) { 3658 throw new RuntimeException( 3659 "Unable to destroy activity " + safeToComponentShortString(r.intent) 3660 + ": " + e.toString(), e); 3661 } 3662 } 3663 } 3664 mActivities.remove(token); 3665 3666 return r; 3667 } 3668 3669 private static String safeToComponentShortString(Intent intent) { 3670 ComponentName component = intent.getComponent(); 3671 return component == null ? "[Unknown]" : component.toShortString(); 3672 } 3673 3674 private final void handleDestroyActivity(IBinder token, boolean finishing, 3675 int configChanges, boolean getNonConfigInstance) { 3676 ActivityRecord r = performDestroyActivity(token, finishing, 3677 configChanges, getNonConfigInstance); 3678 if (r != null) { 3679 WindowManager wm = r.activity.getWindowManager(); 3680 View v = r.activity.mDecor; 3681 if (v != null) { 3682 if (r.activity.mVisibleFromServer) { 3683 mNumVisibleActivities--; 3684 } 3685 IBinder wtoken = v.getWindowToken(); 3686 if (r.activity.mWindowAdded) { 3687 wm.removeViewImmediate(v); 3688 } 3689 if (wtoken != null) { 3690 WindowManagerImpl.getDefault().closeAll(wtoken, 3691 r.activity.getClass().getName(), "Activity"); 3692 } 3693 r.activity.mDecor = null; 3694 } 3695 WindowManagerImpl.getDefault().closeAll(token, 3696 r.activity.getClass().getName(), "Activity"); 3697 3698 // Mocked out contexts won't be participating in the normal 3699 // process lifecycle, but if we're running with a proper 3700 // ApplicationContext we need to have it tear down things 3701 // cleanly. 3702 Context c = r.activity.getBaseContext(); 3703 if (c instanceof ContextImpl) { 3704 ((ContextImpl) c).scheduleFinalCleanup( 3705 r.activity.getClass().getName(), "Activity"); 3706 } 3707 } 3708 if (finishing) { 3709 try { 3710 ActivityManagerNative.getDefault().activityDestroyed(token); 3711 } catch (RemoteException ex) { 3712 // If the system process has died, it's game over for everyone. 3713 } 3714 } 3715 } 3716 3717 private final void handleRelaunchActivity(ActivityRecord tmp, int configChanges) { 3718 // If we are getting ready to gc after going to the background, well 3719 // we are back active so skip it. 3720 unscheduleGcIdler(); 3721 3722 Configuration changedConfig = null; 3723 3724 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity " 3725 + tmp.token + " with configChanges=0x" 3726 + Integer.toHexString(configChanges)); 3727 3728 // First: make sure we have the most recent configuration and most 3729 // recent version of the activity, or skip it if some previous call 3730 // had taken a more recent version. 3731 synchronized (mPackages) { 3732 int N = mRelaunchingActivities.size(); 3733 IBinder token = tmp.token; 3734 tmp = null; 3735 for (int i=0; i<N; i++) { 3736 ActivityRecord r = mRelaunchingActivities.get(i); 3737 if (r.token == token) { 3738 tmp = r; 3739 mRelaunchingActivities.remove(i); 3740 i--; 3741 N--; 3742 } 3743 } 3744 3745 if (tmp == null) { 3746 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!"); 3747 return; 3748 } 3749 3750 if (mPendingConfiguration != null) { 3751 changedConfig = mPendingConfiguration; 3752 mPendingConfiguration = null; 3753 } 3754 } 3755 3756 if (tmp.createdConfig != null) { 3757 // If the activity manager is passing us its current config, 3758 // assume that is really what we want regardless of what we 3759 // may have pending. 3760 if (mConfiguration == null 3761 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration) 3762 && mConfiguration.diff(tmp.createdConfig) != 0)) { 3763 if (changedConfig == null 3764 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) { 3765 changedConfig = tmp.createdConfig; 3766 } 3767 } 3768 } 3769 3770 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity " 3771 + tmp.token + ": changedConfig=" + changedConfig); 3772 3773 // If there was a pending configuration change, execute it first. 3774 if (changedConfig != null) { 3775 handleConfigurationChanged(changedConfig); 3776 } 3777 3778 ActivityRecord r = mActivities.get(tmp.token); 3779 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r); 3780 if (r == null) { 3781 return; 3782 } 3783 3784 r.activity.mConfigChangeFlags |= configChanges; 3785 Intent currentIntent = r.activity.mIntent; 3786 3787 Bundle savedState = null; 3788 if (!r.paused) { 3789 savedState = performPauseActivity(r.token, false, true); 3790 } 3791 3792 handleDestroyActivity(r.token, false, configChanges, true); 3793 3794 r.activity = null; 3795 r.window = null; 3796 r.hideForNow = false; 3797 r.nextIdle = null; 3798 // Merge any pending results and pending intents; don't just replace them 3799 if (tmp.pendingResults != null) { 3800 if (r.pendingResults == null) { 3801 r.pendingResults = tmp.pendingResults; 3802 } else { 3803 r.pendingResults.addAll(tmp.pendingResults); 3804 } 3805 } 3806 if (tmp.pendingIntents != null) { 3807 if (r.pendingIntents == null) { 3808 r.pendingIntents = tmp.pendingIntents; 3809 } else { 3810 r.pendingIntents.addAll(tmp.pendingIntents); 3811 } 3812 } 3813 r.startsNotResumed = tmp.startsNotResumed; 3814 if (savedState != null) { 3815 r.state = savedState; 3816 } 3817 3818 handleLaunchActivity(r, currentIntent); 3819 } 3820 3821 private final void handleRequestThumbnail(IBinder token) { 3822 ActivityRecord r = mActivities.get(token); 3823 Bitmap thumbnail = createThumbnailBitmap(r); 3824 CharSequence description = null; 3825 try { 3826 description = r.activity.onCreateDescription(); 3827 } catch (Exception e) { 3828 if (!mInstrumentation.onException(r.activity, e)) { 3829 throw new RuntimeException( 3830 "Unable to create description of activity " 3831 + r.intent.getComponent().toShortString() 3832 + ": " + e.toString(), e); 3833 } 3834 } 3835 //System.out.println("Reporting top thumbnail " + thumbnail); 3836 try { 3837 ActivityManagerNative.getDefault().reportThumbnail( 3838 token, thumbnail, description); 3839 } catch (RemoteException ex) { 3840 } 3841 } 3842 3843 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked( 3844 boolean allActivities, Configuration newConfig) { 3845 ArrayList<ComponentCallbacks> callbacks 3846 = new ArrayList<ComponentCallbacks>(); 3847 3848 if (mActivities.size() > 0) { 3849 Iterator<ActivityRecord> it = mActivities.values().iterator(); 3850 while (it.hasNext()) { 3851 ActivityRecord ar = it.next(); 3852 Activity a = ar.activity; 3853 if (a != null) { 3854 if (!ar.activity.mFinished && (allActivities || 3855 (a != null && !ar.paused))) { 3856 // If the activity is currently resumed, its configuration 3857 // needs to change right now. 3858 callbacks.add(a); 3859 } else if (newConfig != null) { 3860 // Otherwise, we will tell it about the change 3861 // the next time it is resumed or shown. Note that 3862 // the activity manager may, before then, decide the 3863 // activity needs to be destroyed to handle its new 3864 // configuration. 3865 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity " 3866 + ar.activityInfo.name + " newConfig=" + newConfig); 3867 ar.newConfig = newConfig; 3868 } 3869 } 3870 } 3871 } 3872 if (mServices.size() > 0) { 3873 Iterator<Service> it = mServices.values().iterator(); 3874 while (it.hasNext()) { 3875 callbacks.add(it.next()); 3876 } 3877 } 3878 synchronized (mProviderMap) { 3879 if (mLocalProviders.size() > 0) { 3880 Iterator<ProviderRecord> it = mLocalProviders.values().iterator(); 3881 while (it.hasNext()) { 3882 callbacks.add(it.next().mLocalProvider); 3883 } 3884 } 3885 } 3886 final int N = mAllApplications.size(); 3887 for (int i=0; i<N; i++) { 3888 callbacks.add(mAllApplications.get(i)); 3889 } 3890 3891 return callbacks; 3892 } 3893 3894 private final void performConfigurationChanged( 3895 ComponentCallbacks cb, Configuration config) { 3896 // Only for Activity objects, check that they actually call up to their 3897 // superclass implementation. ComponentCallbacks is an interface, so 3898 // we check the runtime type and act accordingly. 3899 Activity activity = (cb instanceof Activity) ? (Activity) cb : null; 3900 if (activity != null) { 3901 activity.mCalled = false; 3902 } 3903 3904 boolean shouldChangeConfig = false; 3905 if ((activity == null) || (activity.mCurrentConfig == null)) { 3906 shouldChangeConfig = true; 3907 } else { 3908 3909 // If the new config is the same as the config this Activity 3910 // is already running with then don't bother calling 3911 // onConfigurationChanged 3912 int diff = activity.mCurrentConfig.diff(config); 3913 if (diff != 0) { 3914 3915 // If this activity doesn't handle any of the config changes 3916 // then don't bother calling onConfigurationChanged as we're 3917 // going to destroy it. 3918 if ((~activity.mActivityInfo.configChanges & diff) == 0) { 3919 shouldChangeConfig = true; 3920 } 3921 } 3922 } 3923 3924 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb 3925 + ": shouldChangeConfig=" + shouldChangeConfig); 3926 if (shouldChangeConfig) { 3927 cb.onConfigurationChanged(config); 3928 3929 if (activity != null) { 3930 if (!activity.mCalled) { 3931 throw new SuperNotCalledException( 3932 "Activity " + activity.getLocalClassName() + 3933 " did not call through to super.onConfigurationChanged()"); 3934 } 3935 activity.mConfigChangeFlags = 0; 3936 activity.mCurrentConfig = new Configuration(config); 3937 } 3938 } 3939 } 3940 3941 final boolean applyConfigurationToResourcesLocked(Configuration config) { 3942 if (mResConfiguration == null) { 3943 mResConfiguration = new Configuration(); 3944 } 3945 if (!mResConfiguration.isOtherSeqNewer(config)) { 3946 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq=" 3947 + mResConfiguration.seq + ", newSeq=" + config.seq); 3948 return false; 3949 } 3950 int changes = mResConfiguration.updateFrom(config); 3951 DisplayMetrics dm = getDisplayMetricsLocked(true); 3952 3953 // set it for java, this also affects newly created Resources 3954 if (config.locale != null) { 3955 Locale.setDefault(config.locale); 3956 } 3957 3958 Resources.updateSystemConfiguration(config, dm); 3959 3960 ContextImpl.ApplicationPackageManager.configurationChanged(); 3961 //Slog.i(TAG, "Configuration changed in " + currentPackageName()); 3962 3963 Iterator<WeakReference<Resources>> it = 3964 mActiveResources.values().iterator(); 3965 //Iterator<Map.Entry<String, WeakReference<Resources>>> it = 3966 // mActiveResources.entrySet().iterator(); 3967 while (it.hasNext()) { 3968 WeakReference<Resources> v = it.next(); 3969 Resources r = v.get(); 3970 if (r != null) { 3971 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources " 3972 + r + " config to: " + config); 3973 r.updateConfiguration(config, dm); 3974 //Slog.i(TAG, "Updated app resources " + v.getKey() 3975 // + " " + r + ": " + r.getConfiguration()); 3976 } else { 3977 //Slog.i(TAG, "Removing old resources " + v.getKey()); 3978 it.remove(); 3979 } 3980 } 3981 3982 return changes != 0; 3983 } 3984 3985 final void handleConfigurationChanged(Configuration config) { 3986 3987 ArrayList<ComponentCallbacks> callbacks = null; 3988 3989 synchronized (mPackages) { 3990 if (mPendingConfiguration != null) { 3991 if (!mPendingConfiguration.isOtherSeqNewer(config)) { 3992 config = mPendingConfiguration; 3993 } 3994 mPendingConfiguration = null; 3995 } 3996 3997 if (config == null) { 3998 return; 3999 } 4000 4001 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: " 4002 + config); 4003 4004 applyConfigurationToResourcesLocked(config); 4005 4006 if (mConfiguration == null) { 4007 mConfiguration = new Configuration(); 4008 } 4009 if (!mConfiguration.isOtherSeqNewer(config)) { 4010 return; 4011 } 4012 mConfiguration.updateFrom(config); 4013 4014 callbacks = collectComponentCallbacksLocked(false, config); 4015 } 4016 4017 if (callbacks != null) { 4018 final int N = callbacks.size(); 4019 for (int i=0; i<N; i++) { 4020 performConfigurationChanged(callbacks.get(i), config); 4021 } 4022 } 4023 } 4024 4025 final void handleActivityConfigurationChanged(IBinder token) { 4026 ActivityRecord r = mActivities.get(token); 4027 if (r == null || r.activity == null) { 4028 return; 4029 } 4030 4031 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: " 4032 + r.activityInfo.name); 4033 4034 performConfigurationChanged(r.activity, mConfiguration); 4035 } 4036 4037 final void handleProfilerControl(boolean start, ProfilerControlData pcd) { 4038 if (start) { 4039 try { 4040 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(), 4041 8 * 1024 * 1024, 0); 4042 } catch (RuntimeException e) { 4043 Slog.w(TAG, "Profiling failed on path " + pcd.path 4044 + " -- can the process access this path?"); 4045 } finally { 4046 try { 4047 pcd.fd.close(); 4048 } catch (IOException e) { 4049 Slog.w(TAG, "Failure closing profile fd", e); 4050 } 4051 } 4052 } else { 4053 Debug.stopMethodTracing(); 4054 } 4055 } 4056 4057 final void handleLowMemory() { 4058 ArrayList<ComponentCallbacks> callbacks 4059 = new ArrayList<ComponentCallbacks>(); 4060 4061 synchronized (mPackages) { 4062 callbacks = collectComponentCallbacksLocked(true, null); 4063 } 4064 4065 final int N = callbacks.size(); 4066 for (int i=0; i<N; i++) { 4067 callbacks.get(i).onLowMemory(); 4068 } 4069 4070 // Ask SQLite to free up as much memory as it can, mostly from its page caches. 4071 if (Process.myUid() != Process.SYSTEM_UID) { 4072 int sqliteReleased = SQLiteDatabase.releaseMemory(); 4073 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased); 4074 } 4075 4076 // Ask graphics to free up as much as possible (font/image caches) 4077 Canvas.freeCaches(); 4078 4079 BinderInternal.forceGc("mem"); 4080 } 4081 4082 private final void handleBindApplication(AppBindData data) { 4083 mBoundApplication = data; 4084 mConfiguration = new Configuration(data.config); 4085 4086 // send up app name; do this *before* waiting for debugger 4087 Process.setArgV0(data.processName); 4088 android.ddm.DdmHandleAppName.setAppName(data.processName); 4089 4090 /* 4091 * Before spawning a new process, reset the time zone to be the system time zone. 4092 * This needs to be done because the system time zone could have changed after the 4093 * the spawning of this process. Without doing this this process would have the incorrect 4094 * system time zone. 4095 */ 4096 TimeZone.setDefault(null); 4097 4098 /* 4099 * Initialize the default locale in this process for the reasons we set the time zone. 4100 */ 4101 Locale.setDefault(data.config.locale); 4102 4103 /* 4104 * Update the system configuration since its preloaded and might not 4105 * reflect configuration changes. The configuration object passed 4106 * in AppBindData can be safely assumed to be up to date 4107 */ 4108 Resources.getSystem().updateConfiguration(mConfiguration, null); 4109 4110 data.info = getPackageInfoNoCheck(data.appInfo); 4111 4112 /** 4113 * Switch this process to density compatibility mode if needed. 4114 */ 4115 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) 4116 == 0) { 4117 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT); 4118 } 4119 4120 if (data.debugMode != IApplicationThread.DEBUG_OFF) { 4121 // XXX should have option to change the port. 4122 Debug.changeDebugPort(8100); 4123 if (data.debugMode == IApplicationThread.DEBUG_WAIT) { 4124 Slog.w(TAG, "Application " + data.info.getPackageName() 4125 + " is waiting for the debugger on port 8100..."); 4126 4127 IActivityManager mgr = ActivityManagerNative.getDefault(); 4128 try { 4129 mgr.showWaitingForDebugger(mAppThread, true); 4130 } catch (RemoteException ex) { 4131 } 4132 4133 Debug.waitForDebugger(); 4134 4135 try { 4136 mgr.showWaitingForDebugger(mAppThread, false); 4137 } catch (RemoteException ex) { 4138 } 4139 4140 } else { 4141 Slog.w(TAG, "Application " + data.info.getPackageName() 4142 + " can be debugged on port 8100..."); 4143 } 4144 } 4145 4146 if (data.instrumentationName != null) { 4147 ContextImpl appContext = new ContextImpl(); 4148 appContext.init(data.info, null, this); 4149 InstrumentationInfo ii = null; 4150 try { 4151 ii = appContext.getPackageManager(). 4152 getInstrumentationInfo(data.instrumentationName, 0); 4153 } catch (PackageManager.NameNotFoundException e) { 4154 } 4155 if (ii == null) { 4156 throw new RuntimeException( 4157 "Unable to find instrumentation info for: " 4158 + data.instrumentationName); 4159 } 4160 4161 mInstrumentationAppDir = ii.sourceDir; 4162 mInstrumentationAppPackage = ii.packageName; 4163 mInstrumentedAppDir = data.info.getAppDir(); 4164 4165 ApplicationInfo instrApp = new ApplicationInfo(); 4166 instrApp.packageName = ii.packageName; 4167 instrApp.sourceDir = ii.sourceDir; 4168 instrApp.publicSourceDir = ii.publicSourceDir; 4169 instrApp.dataDir = ii.dataDir; 4170 PackageInfo pi = getPackageInfo(instrApp, 4171 appContext.getClassLoader(), false, true); 4172 ContextImpl instrContext = new ContextImpl(); 4173 instrContext.init(pi, null, this); 4174 4175 try { 4176 java.lang.ClassLoader cl = instrContext.getClassLoader(); 4177 mInstrumentation = (Instrumentation) 4178 cl.loadClass(data.instrumentationName.getClassName()).newInstance(); 4179 } catch (Exception e) { 4180 throw new RuntimeException( 4181 "Unable to instantiate instrumentation " 4182 + data.instrumentationName + ": " + e.toString(), e); 4183 } 4184 4185 mInstrumentation.init(this, instrContext, appContext, 4186 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher); 4187 4188 if (data.profileFile != null && !ii.handleProfiling) { 4189 data.handlingProfiling = true; 4190 File file = new File(data.profileFile); 4191 file.getParentFile().mkdirs(); 4192 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024); 4193 } 4194 4195 try { 4196 mInstrumentation.onCreate(data.instrumentationArgs); 4197 } 4198 catch (Exception e) { 4199 throw new RuntimeException( 4200 "Exception thrown in onCreate() of " 4201 + data.instrumentationName + ": " + e.toString(), e); 4202 } 4203 4204 } else { 4205 mInstrumentation = new Instrumentation(); 4206 } 4207 4208 // If the app is being launched for full backup or restore, bring it up in 4209 // a restricted environment with the base application class. 4210 Application app = data.info.makeApplication(data.restrictedBackupMode, null); 4211 mInitialApplication = app; 4212 4213 List<ProviderInfo> providers = data.providers; 4214 if (providers != null) { 4215 installContentProviders(app, providers); 4216 // For process that contain content providers, we want to 4217 // ensure that the JIT is enabled "at some point". 4218 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000); 4219 } 4220 4221 try { 4222 mInstrumentation.callApplicationOnCreate(app); 4223 } catch (Exception e) { 4224 if (!mInstrumentation.onException(app, e)) { 4225 throw new RuntimeException( 4226 "Unable to create application " + app.getClass().getName() 4227 + ": " + e.toString(), e); 4228 } 4229 } 4230 } 4231 4232 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) { 4233 IActivityManager am = ActivityManagerNative.getDefault(); 4234 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) { 4235 Debug.stopMethodTracing(); 4236 } 4237 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault() 4238 // + ", app thr: " + mAppThread); 4239 try { 4240 am.finishInstrumentation(mAppThread, resultCode, results); 4241 } catch (RemoteException ex) { 4242 } 4243 } 4244 4245 private final void installContentProviders( 4246 Context context, List<ProviderInfo> providers) { 4247 final ArrayList<IActivityManager.ContentProviderHolder> results = 4248 new ArrayList<IActivityManager.ContentProviderHolder>(); 4249 4250 Iterator<ProviderInfo> i = providers.iterator(); 4251 while (i.hasNext()) { 4252 ProviderInfo cpi = i.next(); 4253 StringBuilder buf = new StringBuilder(128); 4254 buf.append("Publishing provider "); 4255 buf.append(cpi.authority); 4256 buf.append(": "); 4257 buf.append(cpi.name); 4258 Log.i(TAG, buf.toString()); 4259 IContentProvider cp = installProvider(context, null, cpi, false); 4260 if (cp != null) { 4261 IActivityManager.ContentProviderHolder cph = 4262 new IActivityManager.ContentProviderHolder(cpi); 4263 cph.provider = cp; 4264 results.add(cph); 4265 // Don't ever unload this provider from the process. 4266 synchronized(mProviderMap) { 4267 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000)); 4268 } 4269 } 4270 } 4271 4272 try { 4273 ActivityManagerNative.getDefault().publishContentProviders( 4274 getApplicationThread(), results); 4275 } catch (RemoteException ex) { 4276 } 4277 } 4278 4279 private final IContentProvider getProvider(Context context, String name) { 4280 synchronized(mProviderMap) { 4281 final ProviderRecord pr = mProviderMap.get(name); 4282 if (pr != null) { 4283 return pr.mProvider; 4284 } 4285 } 4286 4287 IActivityManager.ContentProviderHolder holder = null; 4288 try { 4289 holder = ActivityManagerNative.getDefault().getContentProvider( 4290 getApplicationThread(), name); 4291 } catch (RemoteException ex) { 4292 } 4293 if (holder == null) { 4294 Slog.e(TAG, "Failed to find provider info for " + name); 4295 return null; 4296 } 4297 if (holder.permissionFailure != null) { 4298 throw new SecurityException("Permission " + holder.permissionFailure 4299 + " required for provider " + name); 4300 } 4301 4302 IContentProvider prov = installProvider(context, holder.provider, 4303 holder.info, true); 4304 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded); 4305 if (holder.noReleaseNeeded || holder.provider == null) { 4306 // We are not going to release the provider if it is an external 4307 // provider that doesn't care about being released, or if it is 4308 // a local provider running in this process. 4309 //Slog.i(TAG, "*** NO RELEASE NEEDED"); 4310 synchronized(mProviderMap) { 4311 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000)); 4312 } 4313 } 4314 return prov; 4315 } 4316 4317 public final IContentProvider acquireProvider(Context c, String name) { 4318 IContentProvider provider = getProvider(c, name); 4319 if(provider == null) 4320 return null; 4321 IBinder jBinder = provider.asBinder(); 4322 synchronized(mProviderMap) { 4323 ProviderRefCount prc = mProviderRefCountMap.get(jBinder); 4324 if(prc == null) { 4325 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1)); 4326 } else { 4327 prc.count++; 4328 } //end else 4329 } //end synchronized 4330 return provider; 4331 } 4332 4333 public final boolean releaseProvider(IContentProvider provider) { 4334 if(provider == null) { 4335 return false; 4336 } 4337 IBinder jBinder = provider.asBinder(); 4338 synchronized(mProviderMap) { 4339 ProviderRefCount prc = mProviderRefCountMap.get(jBinder); 4340 if(prc == null) { 4341 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldnt be here"); 4342 return false; 4343 } else { 4344 prc.count--; 4345 if(prc.count == 0) { 4346 // Schedule the actual remove asynchronously, since we 4347 // don't know the context this will be called in. 4348 // TODO: it would be nice to post a delayed message, so 4349 // if we come back and need the same provider quickly 4350 // we will still have it available. 4351 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider); 4352 mH.sendMessage(msg); 4353 } //end if 4354 } //end else 4355 } //end synchronized 4356 return true; 4357 } 4358 4359 final void completeRemoveProvider(IContentProvider provider) { 4360 IBinder jBinder = provider.asBinder(); 4361 String name = null; 4362 synchronized(mProviderMap) { 4363 ProviderRefCount prc = mProviderRefCountMap.get(jBinder); 4364 if(prc != null && prc.count == 0) { 4365 mProviderRefCountMap.remove(jBinder); 4366 //invoke removeProvider to dereference provider 4367 name = removeProviderLocked(provider); 4368 } 4369 } 4370 4371 if (name != null) { 4372 try { 4373 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " + 4374 "ActivityManagerNative.removeContentProvider(" + name); 4375 ActivityManagerNative.getDefault().removeContentProvider( 4376 getApplicationThread(), name); 4377 } catch (RemoteException e) { 4378 //do nothing content provider object is dead any way 4379 } //end catch 4380 } 4381 } 4382 4383 public final String removeProviderLocked(IContentProvider provider) { 4384 if (provider == null) { 4385 return null; 4386 } 4387 IBinder providerBinder = provider.asBinder(); 4388 4389 String name = null; 4390 4391 // remove the provider from mProviderMap 4392 Iterator<ProviderRecord> iter = mProviderMap.values().iterator(); 4393 while (iter.hasNext()) { 4394 ProviderRecord pr = iter.next(); 4395 IBinder myBinder = pr.mProvider.asBinder(); 4396 if (myBinder == providerBinder) { 4397 //find if its published by this process itself 4398 if(pr.mLocalProvider != null) { 4399 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning"); 4400 return name; 4401 } 4402 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " + 4403 "death recipient"); 4404 //content provider is in another process 4405 myBinder.unlinkToDeath(pr, 0); 4406 iter.remove(); 4407 //invoke remove only once for the very first name seen 4408 if(name == null) { 4409 name = pr.mName; 4410 } 4411 } //end if myBinder 4412 } //end while iter 4413 4414 return name; 4415 } 4416 4417 final void removeDeadProvider(String name, IContentProvider provider) { 4418 synchronized(mProviderMap) { 4419 ProviderRecord pr = mProviderMap.get(name); 4420 if (pr.mProvider.asBinder() == provider.asBinder()) { 4421 Slog.i(TAG, "Removing dead content provider: " + name); 4422 ProviderRecord removed = mProviderMap.remove(name); 4423 if (removed != null) { 4424 removed.mProvider.asBinder().unlinkToDeath(removed, 0); 4425 } 4426 } 4427 } 4428 } 4429 4430 final void removeDeadProviderLocked(String name, IContentProvider provider) { 4431 ProviderRecord pr = mProviderMap.get(name); 4432 if (pr.mProvider.asBinder() == provider.asBinder()) { 4433 Slog.i(TAG, "Removing dead content provider: " + name); 4434 ProviderRecord removed = mProviderMap.remove(name); 4435 if (removed != null) { 4436 removed.mProvider.asBinder().unlinkToDeath(removed, 0); 4437 } 4438 } 4439 } 4440 4441 private final IContentProvider installProvider(Context context, 4442 IContentProvider provider, ProviderInfo info, boolean noisy) { 4443 ContentProvider localProvider = null; 4444 if (provider == null) { 4445 if (noisy) { 4446 Slog.d(TAG, "Loading provider " + info.authority + ": " 4447 + info.name); 4448 } 4449 Context c = null; 4450 ApplicationInfo ai = info.applicationInfo; 4451 if (context.getPackageName().equals(ai.packageName)) { 4452 c = context; 4453 } else if (mInitialApplication != null && 4454 mInitialApplication.getPackageName().equals(ai.packageName)) { 4455 c = mInitialApplication; 4456 } else { 4457 try { 4458 c = context.createPackageContext(ai.packageName, 4459 Context.CONTEXT_INCLUDE_CODE); 4460 } catch (PackageManager.NameNotFoundException e) { 4461 } 4462 } 4463 if (c == null) { 4464 Slog.w(TAG, "Unable to get context for package " + 4465 ai.packageName + 4466 " while loading content provider " + 4467 info.name); 4468 return null; 4469 } 4470 try { 4471 final java.lang.ClassLoader cl = c.getClassLoader(); 4472 localProvider = (ContentProvider)cl. 4473 loadClass(info.name).newInstance(); 4474 provider = localProvider.getIContentProvider(); 4475 if (provider == null) { 4476 Slog.e(TAG, "Failed to instantiate class " + 4477 info.name + " from sourceDir " + 4478 info.applicationInfo.sourceDir); 4479 return null; 4480 } 4481 if (Config.LOGV) Slog.v( 4482 TAG, "Instantiating local provider " + info.name); 4483 // XXX Need to create the correct context for this provider. 4484 localProvider.attachInfo(c, info); 4485 } catch (java.lang.Exception e) { 4486 if (!mInstrumentation.onException(null, e)) { 4487 throw new RuntimeException( 4488 "Unable to get provider " + info.name 4489 + ": " + e.toString(), e); 4490 } 4491 return null; 4492 } 4493 } else if (localLOGV) { 4494 Slog.v(TAG, "Installing external provider " + info.authority + ": " 4495 + info.name); 4496 } 4497 4498 synchronized (mProviderMap) { 4499 // Cache the pointer for the remote provider. 4500 String names[] = PATTERN_SEMICOLON.split(info.authority); 4501 for (int i=0; i<names.length; i++) { 4502 ProviderRecord pr = new ProviderRecord(names[i], provider, 4503 localProvider); 4504 try { 4505 provider.asBinder().linkToDeath(pr, 0); 4506 mProviderMap.put(names[i], pr); 4507 } catch (RemoteException e) { 4508 return null; 4509 } 4510 } 4511 if (localProvider != null) { 4512 mLocalProviders.put(provider.asBinder(), 4513 new ProviderRecord(null, provider, localProvider)); 4514 } 4515 } 4516 4517 return provider; 4518 } 4519 4520 private final void attach(boolean system) { 4521 sThreadLocal.set(this); 4522 mSystemThread = system; 4523 if (!system) { 4524 ViewRoot.addFirstDrawHandler(new Runnable() { 4525 public void run() { 4526 ensureJitEnabled(); 4527 } 4528 }); 4529 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>"); 4530 RuntimeInit.setApplicationObject(mAppThread.asBinder()); 4531 IActivityManager mgr = ActivityManagerNative.getDefault(); 4532 try { 4533 mgr.attachApplication(mAppThread); 4534 } catch (RemoteException ex) { 4535 } 4536 } else { 4537 // Don't set application object here -- if the system crashes, 4538 // we can't display an alert, we just want to die die die. 4539 android.ddm.DdmHandleAppName.setAppName("system_process"); 4540 try { 4541 mInstrumentation = new Instrumentation(); 4542 ContextImpl context = new ContextImpl(); 4543 context.init(getSystemContext().mPackageInfo, null, this); 4544 Application app = Instrumentation.newApplication(Application.class, context); 4545 mAllApplications.add(app); 4546 mInitialApplication = app; 4547 app.onCreate(); 4548 } catch (Exception e) { 4549 throw new RuntimeException( 4550 "Unable to instantiate Application():" + e.toString(), e); 4551 } 4552 } 4553 4554 ViewRoot.addConfigCallback(new ComponentCallbacks() { 4555 public void onConfigurationChanged(Configuration newConfig) { 4556 synchronized (mPackages) { 4557 // We need to apply this change to the resources 4558 // immediately, because upon returning the view 4559 // hierarchy will be informed about it. 4560 if (applyConfigurationToResourcesLocked(newConfig)) { 4561 // This actually changed the resources! Tell 4562 // everyone about it. 4563 if (mPendingConfiguration == null || 4564 mPendingConfiguration.isOtherSeqNewer(newConfig)) { 4565 mPendingConfiguration = newConfig; 4566 4567 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig); 4568 } 4569 } 4570 } 4571 } 4572 public void onLowMemory() { 4573 } 4574 }); 4575 } 4576 4577 private final void detach() 4578 { 4579 sThreadLocal.set(null); 4580 } 4581 4582 public static final ActivityThread systemMain() { 4583 ActivityThread thread = new ActivityThread(); 4584 thread.attach(true); 4585 return thread; 4586 } 4587 4588 public final void installSystemProviders(List providers) { 4589 if (providers != null) { 4590 installContentProviders(mInitialApplication, 4591 (List<ProviderInfo>)providers); 4592 } 4593 } 4594 4595 public static final void main(String[] args) { 4596 SamplingProfilerIntegration.start(); 4597 4598 Process.setArgV0("<pre-initialized>"); 4599 4600 Looper.prepareMainLooper(); 4601 4602 ActivityThread thread = new ActivityThread(); 4603 thread.attach(false); 4604 4605 Looper.loop(); 4606 4607 if (Process.supportsProcesses()) { 4608 throw new RuntimeException("Main thread loop unexpectedly exited"); 4609 } 4610 4611 thread.detach(); 4612 String name = (thread.mInitialApplication != null) 4613 ? thread.mInitialApplication.getPackageName() 4614 : "<unknown>"; 4615 Slog.i(TAG, "Main thread of " + name + " is now exiting"); 4616 } 4617} 4618