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