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