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