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