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