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