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