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