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