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