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