ActivityThread.java revision 62f20ecf492d2b29881bba307c79ff55e68760e6
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 Slog.i(TAG, "Launch: profileFd=" + r.profileFile + " stop=" + r.autoStopProfiler); 1947 if (r.profileFd != null) { 1948 mBoundApplication.setProfiler(r.profileFile, r.profileFd); 1949 mBoundApplication.startProfiling(); 1950 mBoundApplication.autoStopProfiler = r.autoStopProfiler; 1951 } 1952 1953 if (localLOGV) Slog.v( 1954 TAG, "Handling launch of " + r); 1955 Activity a = performLaunchActivity(r, customIntent); 1956 1957 if (a != null) { 1958 r.createdConfig = new Configuration(mConfiguration); 1959 Bundle oldState = r.state; 1960 handleResumeActivity(r.token, false, r.isForward); 1961 1962 if (!r.activity.mFinished && r.startsNotResumed) { 1963 // The activity manager actually wants this one to start out 1964 // paused, because it needs to be visible but isn't in the 1965 // foreground. We accomplish this by going through the 1966 // normal startup (because activities expect to go through 1967 // onResume() the first time they run, before their window 1968 // is displayed), and then pausing it. However, in this case 1969 // we do -not- need to do the full pause cycle (of freezing 1970 // and such) because the activity manager assumes it can just 1971 // retain the current state it has. 1972 try { 1973 r.activity.mCalled = false; 1974 mInstrumentation.callActivityOnPause(r.activity); 1975 // We need to keep around the original state, in case 1976 // we need to be created again. 1977 r.state = oldState; 1978 if (!r.activity.mCalled) { 1979 throw new SuperNotCalledException( 1980 "Activity " + r.intent.getComponent().toShortString() + 1981 " did not call through to super.onPause()"); 1982 } 1983 1984 } catch (SuperNotCalledException e) { 1985 throw e; 1986 1987 } catch (Exception e) { 1988 if (!mInstrumentation.onException(r.activity, e)) { 1989 throw new RuntimeException( 1990 "Unable to pause activity " 1991 + r.intent.getComponent().toShortString() 1992 + ": " + e.toString(), e); 1993 } 1994 } 1995 r.paused = true; 1996 } 1997 } else { 1998 // If there was an error, for any reason, tell the activity 1999 // manager to stop us. 2000 try { 2001 ActivityManagerNative.getDefault() 2002 .finishActivity(r.token, Activity.RESULT_CANCELED, null); 2003 } catch (RemoteException ex) { 2004 // Ignore 2005 } 2006 } 2007 } 2008 2009 private void deliverNewIntents(ActivityClientRecord r, 2010 List<Intent> intents) { 2011 final int N = intents.size(); 2012 for (int i=0; i<N; i++) { 2013 Intent intent = intents.get(i); 2014 intent.setExtrasClassLoader(r.activity.getClassLoader()); 2015 r.activity.mFragments.noteStateNotSaved(); 2016 mInstrumentation.callActivityOnNewIntent(r.activity, intent); 2017 } 2018 } 2019 2020 public final void performNewIntents(IBinder token, 2021 List<Intent> intents) { 2022 ActivityClientRecord r = mActivities.get(token); 2023 if (r != null) { 2024 final boolean resumed = !r.paused; 2025 if (resumed) { 2026 r.activity.mTemporaryPause = true; 2027 mInstrumentation.callActivityOnPause(r.activity); 2028 } 2029 deliverNewIntents(r, intents); 2030 if (resumed) { 2031 r.activity.performResume(); 2032 r.activity.mTemporaryPause = false; 2033 } 2034 } 2035 } 2036 2037 private void handleNewIntent(NewIntentData data) { 2038 performNewIntents(data.token, data.intents); 2039 } 2040 2041 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>(); 2042 2043 /** 2044 * Return the Intent that's currently being handled by a 2045 * BroadcastReceiver on this thread, or null if none. 2046 * @hide 2047 */ 2048 public static Intent getIntentBeingBroadcast() { 2049 return sCurrentBroadcastIntent.get(); 2050 } 2051 2052 private void handleReceiver(ReceiverData data) { 2053 // If we are getting ready to gc after going to the background, well 2054 // we are back active so skip it. 2055 unscheduleGcIdler(); 2056 2057 String component = data.intent.getComponent().getClassName(); 2058 2059 LoadedApk packageInfo = getPackageInfoNoCheck( 2060 data.info.applicationInfo, data.compatInfo); 2061 2062 IActivityManager mgr = ActivityManagerNative.getDefault(); 2063 2064 BroadcastReceiver receiver; 2065 try { 2066 java.lang.ClassLoader cl = packageInfo.getClassLoader(); 2067 data.intent.setExtrasClassLoader(cl); 2068 data.setExtrasClassLoader(cl); 2069 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance(); 2070 } catch (Exception e) { 2071 if (DEBUG_BROADCAST) Slog.i(TAG, 2072 "Finishing failed broadcast to " + data.intent.getComponent()); 2073 data.sendFinished(mgr); 2074 throw new RuntimeException( 2075 "Unable to instantiate receiver " + component 2076 + ": " + e.toString(), e); 2077 } 2078 2079 try { 2080 Application app = packageInfo.makeApplication(false, mInstrumentation); 2081 2082 if (localLOGV) Slog.v( 2083 TAG, "Performing receive of " + data.intent 2084 + ": app=" + app 2085 + ", appName=" + app.getPackageName() 2086 + ", pkg=" + packageInfo.getPackageName() 2087 + ", comp=" + data.intent.getComponent().toShortString() 2088 + ", dir=" + packageInfo.getAppDir()); 2089 2090 ContextImpl context = (ContextImpl)app.getBaseContext(); 2091 sCurrentBroadcastIntent.set(data.intent); 2092 receiver.setPendingResult(data); 2093 receiver.onReceive(context.getReceiverRestrictedContext(), 2094 data.intent); 2095 } catch (Exception e) { 2096 if (DEBUG_BROADCAST) Slog.i(TAG, 2097 "Finishing failed broadcast to " + data.intent.getComponent()); 2098 data.sendFinished(mgr); 2099 if (!mInstrumentation.onException(receiver, e)) { 2100 throw new RuntimeException( 2101 "Unable to start receiver " + component 2102 + ": " + e.toString(), e); 2103 } 2104 } finally { 2105 sCurrentBroadcastIntent.set(null); 2106 } 2107 2108 if (receiver.getPendingResult() != null) { 2109 data.finish(); 2110 } 2111 } 2112 2113 // Instantiate a BackupAgent and tell it that it's alive 2114 private void handleCreateBackupAgent(CreateBackupAgentData data) { 2115 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data); 2116 2117 // no longer idle; we have backup work to do 2118 unscheduleGcIdler(); 2119 2120 // instantiate the BackupAgent class named in the manifest 2121 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo); 2122 String packageName = packageInfo.mPackageName; 2123 if (mBackupAgents.get(packageName) != null) { 2124 Slog.d(TAG, "BackupAgent " + " for " + packageName 2125 + " already exists"); 2126 return; 2127 } 2128 2129 BackupAgent agent = null; 2130 String classname = data.appInfo.backupAgentName; 2131 2132 // full backup operation but no app-supplied agent? use the default implementation 2133 if (classname == null && (data.backupMode == IApplicationThread.BACKUP_MODE_FULL 2134 || data.backupMode == IApplicationThread.BACKUP_MODE_RESTORE_FULL)) { 2135 classname = "android.app.backup.FullBackupAgent"; 2136 } 2137 2138 try { 2139 IBinder binder = null; 2140 try { 2141 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname); 2142 2143 java.lang.ClassLoader cl = packageInfo.getClassLoader(); 2144 agent = (BackupAgent) cl.loadClass(classname).newInstance(); 2145 2146 // set up the agent's context 2147 ContextImpl context = new ContextImpl(); 2148 context.init(packageInfo, null, this); 2149 context.setOuterContext(agent); 2150 agent.attach(context); 2151 2152 agent.onCreate(); 2153 binder = agent.onBind(); 2154 mBackupAgents.put(packageName, agent); 2155 } catch (Exception e) { 2156 // If this is during restore, fail silently; otherwise go 2157 // ahead and let the user see the crash. 2158 Slog.e(TAG, "Agent threw during creation: " + e); 2159 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE 2160 && data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE_FULL) { 2161 throw e; 2162 } 2163 // falling through with 'binder' still null 2164 } 2165 2166 // tell the OS that we're live now 2167 try { 2168 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder); 2169 } catch (RemoteException e) { 2170 // nothing to do. 2171 } 2172 } catch (Exception e) { 2173 throw new RuntimeException("Unable to create BackupAgent " 2174 + classname + ": " + e.toString(), e); 2175 } 2176 } 2177 2178 // Tear down a BackupAgent 2179 private void handleDestroyBackupAgent(CreateBackupAgentData data) { 2180 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data); 2181 2182 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo); 2183 String packageName = packageInfo.mPackageName; 2184 BackupAgent agent = mBackupAgents.get(packageName); 2185 if (agent != null) { 2186 try { 2187 agent.onDestroy(); 2188 } catch (Exception e) { 2189 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo); 2190 e.printStackTrace(); 2191 } 2192 mBackupAgents.remove(packageName); 2193 } else { 2194 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data); 2195 } 2196 } 2197 2198 private void handleCreateService(CreateServiceData data) { 2199 // If we are getting ready to gc after going to the background, well 2200 // we are back active so skip it. 2201 unscheduleGcIdler(); 2202 2203 LoadedApk packageInfo = getPackageInfoNoCheck( 2204 data.info.applicationInfo, data.compatInfo); 2205 Service service = null; 2206 try { 2207 java.lang.ClassLoader cl = packageInfo.getClassLoader(); 2208 service = (Service) cl.loadClass(data.info.name).newInstance(); 2209 } catch (Exception e) { 2210 if (!mInstrumentation.onException(service, e)) { 2211 throw new RuntimeException( 2212 "Unable to instantiate service " + data.info.name 2213 + ": " + e.toString(), e); 2214 } 2215 } 2216 2217 try { 2218 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name); 2219 2220 ContextImpl context = new ContextImpl(); 2221 context.init(packageInfo, null, this); 2222 2223 Application app = packageInfo.makeApplication(false, mInstrumentation); 2224 context.setOuterContext(service); 2225 service.attach(context, this, data.info.name, data.token, app, 2226 ActivityManagerNative.getDefault()); 2227 service.onCreate(); 2228 mServices.put(data.token, service); 2229 try { 2230 ActivityManagerNative.getDefault().serviceDoneExecuting( 2231 data.token, 0, 0, 0); 2232 } catch (RemoteException e) { 2233 // nothing to do. 2234 } 2235 } catch (Exception e) { 2236 if (!mInstrumentation.onException(service, e)) { 2237 throw new RuntimeException( 2238 "Unable to create service " + data.info.name 2239 + ": " + e.toString(), e); 2240 } 2241 } 2242 } 2243 2244 private void handleBindService(BindServiceData data) { 2245 Service s = mServices.get(data.token); 2246 if (s != null) { 2247 try { 2248 data.intent.setExtrasClassLoader(s.getClassLoader()); 2249 try { 2250 if (!data.rebind) { 2251 IBinder binder = s.onBind(data.intent); 2252 ActivityManagerNative.getDefault().publishService( 2253 data.token, data.intent, binder); 2254 } else { 2255 s.onRebind(data.intent); 2256 ActivityManagerNative.getDefault().serviceDoneExecuting( 2257 data.token, 0, 0, 0); 2258 } 2259 ensureJitEnabled(); 2260 } catch (RemoteException ex) { 2261 } 2262 } catch (Exception e) { 2263 if (!mInstrumentation.onException(s, e)) { 2264 throw new RuntimeException( 2265 "Unable to bind to service " + s 2266 + " with " + data.intent + ": " + e.toString(), e); 2267 } 2268 } 2269 } 2270 } 2271 2272 private void handleUnbindService(BindServiceData data) { 2273 Service s = mServices.get(data.token); 2274 if (s != null) { 2275 try { 2276 data.intent.setExtrasClassLoader(s.getClassLoader()); 2277 boolean doRebind = s.onUnbind(data.intent); 2278 try { 2279 if (doRebind) { 2280 ActivityManagerNative.getDefault().unbindFinished( 2281 data.token, data.intent, doRebind); 2282 } else { 2283 ActivityManagerNative.getDefault().serviceDoneExecuting( 2284 data.token, 0, 0, 0); 2285 } 2286 } catch (RemoteException ex) { 2287 } 2288 } catch (Exception e) { 2289 if (!mInstrumentation.onException(s, e)) { 2290 throw new RuntimeException( 2291 "Unable to unbind to service " + s 2292 + " with " + data.intent + ": " + e.toString(), e); 2293 } 2294 } 2295 } 2296 } 2297 2298 private void handleDumpService(DumpComponentInfo info) { 2299 Service s = mServices.get(info.token); 2300 if (s != null) { 2301 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor())); 2302 s.dump(info.fd.getFileDescriptor(), pw, info.args); 2303 pw.flush(); 2304 try { 2305 info.fd.close(); 2306 } catch (IOException e) { 2307 } 2308 } 2309 } 2310 2311 private void handleDumpActivity(DumpComponentInfo info) { 2312 ActivityClientRecord r = mActivities.get(info.token); 2313 if (r != null && r.activity != null) { 2314 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor())); 2315 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args); 2316 pw.flush(); 2317 try { 2318 info.fd.close(); 2319 } catch (IOException e) { 2320 } 2321 } 2322 } 2323 2324 private void handleServiceArgs(ServiceArgsData data) { 2325 Service s = mServices.get(data.token); 2326 if (s != null) { 2327 try { 2328 if (data.args != null) { 2329 data.args.setExtrasClassLoader(s.getClassLoader()); 2330 } 2331 int res; 2332 if (!data.taskRemoved) { 2333 res = s.onStartCommand(data.args, data.flags, data.startId); 2334 } else { 2335 s.onTaskRemoved(data.args); 2336 res = Service.START_TASK_REMOVED_COMPLETE; 2337 } 2338 2339 QueuedWork.waitToFinish(); 2340 2341 try { 2342 ActivityManagerNative.getDefault().serviceDoneExecuting( 2343 data.token, 1, data.startId, res); 2344 } catch (RemoteException e) { 2345 // nothing to do. 2346 } 2347 ensureJitEnabled(); 2348 } catch (Exception e) { 2349 if (!mInstrumentation.onException(s, e)) { 2350 throw new RuntimeException( 2351 "Unable to start service " + s 2352 + " with " + data.args + ": " + e.toString(), e); 2353 } 2354 } 2355 } 2356 } 2357 2358 private void handleStopService(IBinder token) { 2359 Service s = mServices.remove(token); 2360 if (s != null) { 2361 try { 2362 if (localLOGV) Slog.v(TAG, "Destroying service " + s); 2363 s.onDestroy(); 2364 Context context = s.getBaseContext(); 2365 if (context instanceof ContextImpl) { 2366 final String who = s.getClassName(); 2367 ((ContextImpl) context).scheduleFinalCleanup(who, "Service"); 2368 } 2369 2370 QueuedWork.waitToFinish(); 2371 2372 try { 2373 ActivityManagerNative.getDefault().serviceDoneExecuting( 2374 token, 0, 0, 0); 2375 } catch (RemoteException e) { 2376 // nothing to do. 2377 } 2378 } catch (Exception e) { 2379 if (!mInstrumentation.onException(s, e)) { 2380 throw new RuntimeException( 2381 "Unable to stop service " + s 2382 + ": " + e.toString(), e); 2383 } 2384 } 2385 } 2386 //Slog.i(TAG, "Running services: " + mServices); 2387 } 2388 2389 public final ActivityClientRecord performResumeActivity(IBinder token, 2390 boolean clearHide) { 2391 ActivityClientRecord r = mActivities.get(token); 2392 if (localLOGV) Slog.v(TAG, "Performing resume of " + r 2393 + " finished=" + r.activity.mFinished); 2394 if (r != null && !r.activity.mFinished) { 2395 if (clearHide) { 2396 r.hideForNow = false; 2397 r.activity.mStartedActivity = false; 2398 } 2399 try { 2400 if (r.pendingIntents != null) { 2401 deliverNewIntents(r, r.pendingIntents); 2402 r.pendingIntents = null; 2403 } 2404 if (r.pendingResults != null) { 2405 deliverResults(r, r.pendingResults); 2406 r.pendingResults = null; 2407 } 2408 r.activity.performResume(); 2409 2410 EventLog.writeEvent(LOG_ON_RESUME_CALLED, 2411 r.activity.getComponentName().getClassName()); 2412 2413 r.paused = false; 2414 r.stopped = false; 2415 r.state = null; 2416 } catch (Exception e) { 2417 if (!mInstrumentation.onException(r.activity, e)) { 2418 throw new RuntimeException( 2419 "Unable to resume activity " 2420 + r.intent.getComponent().toShortString() 2421 + ": " + e.toString(), e); 2422 } 2423 } 2424 } 2425 return r; 2426 } 2427 2428 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) { 2429 if (r.mPendingRemoveWindow != null) { 2430 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow); 2431 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken(); 2432 if (wtoken != null) { 2433 WindowManagerImpl.getDefault().closeAll(wtoken, 2434 r.activity.getClass().getName(), "Activity"); 2435 } 2436 } 2437 r.mPendingRemoveWindow = null; 2438 r.mPendingRemoveWindowManager = null; 2439 } 2440 2441 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) { 2442 // If we are getting ready to gc after going to the background, well 2443 // we are back active so skip it. 2444 unscheduleGcIdler(); 2445 2446 ActivityClientRecord r = performResumeActivity(token, clearHide); 2447 2448 if (r != null) { 2449 final Activity a = r.activity; 2450 2451 if (localLOGV) Slog.v( 2452 TAG, "Resume " + r + " started activity: " + 2453 a.mStartedActivity + ", hideForNow: " + r.hideForNow 2454 + ", finished: " + a.mFinished); 2455 2456 final int forwardBit = isForward ? 2457 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0; 2458 2459 // If the window hasn't yet been added to the window manager, 2460 // and this guy didn't finish itself or start another activity, 2461 // then go ahead and add the window. 2462 boolean willBeVisible = !a.mStartedActivity; 2463 if (!willBeVisible) { 2464 try { 2465 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible( 2466 a.getActivityToken()); 2467 } catch (RemoteException e) { 2468 } 2469 } 2470 if (r.window == null && !a.mFinished && willBeVisible) { 2471 r.window = r.activity.getWindow(); 2472 View decor = r.window.getDecorView(); 2473 decor.setVisibility(View.INVISIBLE); 2474 ViewManager wm = a.getWindowManager(); 2475 WindowManager.LayoutParams l = r.window.getAttributes(); 2476 a.mDecor = decor; 2477 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION; 2478 l.softInputMode |= forwardBit; 2479 if (a.mVisibleFromClient) { 2480 a.mWindowAdded = true; 2481 wm.addView(decor, l); 2482 } 2483 2484 // If the window has already been added, but during resume 2485 // we started another activity, then don't yet make the 2486 // window visible. 2487 } else if (!willBeVisible) { 2488 if (localLOGV) Slog.v( 2489 TAG, "Launch " + r + " mStartedActivity set"); 2490 r.hideForNow = true; 2491 } 2492 2493 // Get rid of anything left hanging around. 2494 cleanUpPendingRemoveWindows(r); 2495 2496 // The window is now visible if it has been added, we are not 2497 // simply finishing, and we are not starting another activity. 2498 if (!r.activity.mFinished && willBeVisible 2499 && r.activity.mDecor != null && !r.hideForNow) { 2500 if (r.newConfig != null) { 2501 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity " 2502 + r.activityInfo.name + " with newConfig " + r.newConfig); 2503 performConfigurationChanged(r.activity, r.newConfig); 2504 r.newConfig = null; 2505 } 2506 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" 2507 + isForward); 2508 WindowManager.LayoutParams l = r.window.getAttributes(); 2509 if ((l.softInputMode 2510 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) 2511 != forwardBit) { 2512 l.softInputMode = (l.softInputMode 2513 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)) 2514 | forwardBit; 2515 if (r.activity.mVisibleFromClient) { 2516 ViewManager wm = a.getWindowManager(); 2517 View decor = r.window.getDecorView(); 2518 wm.updateViewLayout(decor, l); 2519 } 2520 } 2521 r.activity.mVisibleFromServer = true; 2522 mNumVisibleActivities++; 2523 if (r.activity.mVisibleFromClient) { 2524 r.activity.makeVisible(); 2525 } 2526 } 2527 2528 if (!r.onlyLocalRequest) { 2529 r.nextIdle = mNewActivities; 2530 mNewActivities = r; 2531 if (localLOGV) Slog.v( 2532 TAG, "Scheduling idle handler for " + r); 2533 Looper.myQueue().addIdleHandler(new Idler()); 2534 } 2535 r.onlyLocalRequest = false; 2536 2537 } else { 2538 // If an exception was thrown when trying to resume, then 2539 // just end this activity. 2540 try { 2541 ActivityManagerNative.getDefault() 2542 .finishActivity(token, Activity.RESULT_CANCELED, null); 2543 } catch (RemoteException ex) { 2544 } 2545 } 2546 } 2547 2548 private int mThumbnailWidth = -1; 2549 private int mThumbnailHeight = -1; 2550 private Bitmap mAvailThumbnailBitmap = null; 2551 private Canvas mThumbnailCanvas = null; 2552 2553 private Bitmap createThumbnailBitmap(ActivityClientRecord r) { 2554 Bitmap thumbnail = mAvailThumbnailBitmap; 2555 try { 2556 if (thumbnail == null) { 2557 int w = mThumbnailWidth; 2558 int h; 2559 if (w < 0) { 2560 Resources res = r.activity.getResources(); 2561 mThumbnailHeight = h = 2562 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height); 2563 2564 mThumbnailWidth = w = 2565 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width); 2566 } else { 2567 h = mThumbnailHeight; 2568 } 2569 2570 // On platforms where we don't want thumbnails, set dims to (0,0) 2571 if ((w > 0) && (h > 0)) { 2572 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT); 2573 thumbnail.eraseColor(0); 2574 } 2575 } 2576 2577 if (thumbnail != null) { 2578 Canvas cv = mThumbnailCanvas; 2579 if (cv == null) { 2580 mThumbnailCanvas = cv = new Canvas(); 2581 } 2582 2583 cv.setBitmap(thumbnail); 2584 if (!r.activity.onCreateThumbnail(thumbnail, cv)) { 2585 mAvailThumbnailBitmap = thumbnail; 2586 thumbnail = null; 2587 } 2588 cv.setBitmap(null); 2589 } 2590 2591 } catch (Exception e) { 2592 if (!mInstrumentation.onException(r.activity, e)) { 2593 throw new RuntimeException( 2594 "Unable to create thumbnail of " 2595 + r.intent.getComponent().toShortString() 2596 + ": " + e.toString(), e); 2597 } 2598 thumbnail = null; 2599 } 2600 2601 return thumbnail; 2602 } 2603 2604 private void handlePauseActivity(IBinder token, boolean finished, 2605 boolean userLeaving, int configChanges) { 2606 ActivityClientRecord r = mActivities.get(token); 2607 if (r != null) { 2608 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r); 2609 if (userLeaving) { 2610 performUserLeavingActivity(r); 2611 } 2612 2613 r.activity.mConfigChangeFlags |= configChanges; 2614 performPauseActivity(token, finished, r.isPreHoneycomb()); 2615 2616 // Make sure any pending writes are now committed. 2617 if (r.isPreHoneycomb()) { 2618 QueuedWork.waitToFinish(); 2619 } 2620 2621 // Tell the activity manager we have paused. 2622 try { 2623 ActivityManagerNative.getDefault().activityPaused(token); 2624 } catch (RemoteException ex) { 2625 } 2626 } 2627 } 2628 2629 final void performUserLeavingActivity(ActivityClientRecord r) { 2630 mInstrumentation.callActivityOnUserLeaving(r.activity); 2631 } 2632 2633 final Bundle performPauseActivity(IBinder token, boolean finished, 2634 boolean saveState) { 2635 ActivityClientRecord r = mActivities.get(token); 2636 return r != null ? performPauseActivity(r, finished, saveState) : null; 2637 } 2638 2639 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished, 2640 boolean saveState) { 2641 if (r.paused) { 2642 if (r.activity.mFinished) { 2643 // If we are finishing, we won't call onResume() in certain cases. 2644 // So here we likewise don't want to call onPause() if the activity 2645 // isn't resumed. 2646 return null; 2647 } 2648 RuntimeException e = new RuntimeException( 2649 "Performing pause of activity that is not resumed: " 2650 + r.intent.getComponent().toShortString()); 2651 Slog.e(TAG, e.getMessage(), e); 2652 } 2653 Bundle state = null; 2654 if (finished) { 2655 r.activity.mFinished = true; 2656 } 2657 try { 2658 // Next have the activity save its current state and managed dialogs... 2659 if (!r.activity.mFinished && saveState) { 2660 state = new Bundle(); 2661 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state); 2662 r.state = state; 2663 } 2664 // Now we are idle. 2665 r.activity.mCalled = false; 2666 mInstrumentation.callActivityOnPause(r.activity); 2667 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName()); 2668 if (!r.activity.mCalled) { 2669 throw new SuperNotCalledException( 2670 "Activity " + r.intent.getComponent().toShortString() + 2671 " did not call through to super.onPause()"); 2672 } 2673 2674 } catch (SuperNotCalledException e) { 2675 throw e; 2676 2677 } catch (Exception e) { 2678 if (!mInstrumentation.onException(r.activity, e)) { 2679 throw new RuntimeException( 2680 "Unable to pause activity " 2681 + r.intent.getComponent().toShortString() 2682 + ": " + e.toString(), e); 2683 } 2684 } 2685 r.paused = true; 2686 2687 // Notify any outstanding on paused listeners 2688 ArrayList<OnActivityPausedListener> listeners; 2689 synchronized (mOnPauseListeners) { 2690 listeners = mOnPauseListeners.remove(r.activity); 2691 } 2692 int size = (listeners != null ? listeners.size() : 0); 2693 for (int i = 0; i < size; i++) { 2694 listeners.get(i).onPaused(r.activity); 2695 } 2696 2697 return state; 2698 } 2699 2700 final void performStopActivity(IBinder token, boolean saveState) { 2701 ActivityClientRecord r = mActivities.get(token); 2702 performStopActivityInner(r, null, false, saveState); 2703 } 2704 2705 private static class StopInfo { 2706 Bitmap thumbnail; 2707 CharSequence description; 2708 } 2709 2710 private class ProviderRefCount { 2711 public int count; 2712 ProviderRefCount(int pCount) { 2713 count = pCount; 2714 } 2715 } 2716 2717 /** 2718 * Core implementation of stopping an activity. Note this is a little 2719 * tricky because the server's meaning of stop is slightly different 2720 * than our client -- for the server, stop means to save state and give 2721 * it the result when it is done, but the window may still be visible. 2722 * For the client, we want to call onStop()/onStart() to indicate when 2723 * the activity's UI visibillity changes. 2724 */ 2725 private void performStopActivityInner(ActivityClientRecord r, 2726 StopInfo info, boolean keepShown, boolean saveState) { 2727 if (localLOGV) Slog.v(TAG, "Performing stop of " + r); 2728 Bundle state = null; 2729 if (r != null) { 2730 if (!keepShown && r.stopped) { 2731 if (r.activity.mFinished) { 2732 // If we are finishing, we won't call onResume() in certain 2733 // cases. So here we likewise don't want to call onStop() 2734 // if the activity isn't resumed. 2735 return; 2736 } 2737 RuntimeException e = new RuntimeException( 2738 "Performing stop of activity that is not resumed: " 2739 + r.intent.getComponent().toShortString()); 2740 Slog.e(TAG, e.getMessage(), e); 2741 } 2742 2743 if (info != null) { 2744 try { 2745 // First create a thumbnail for the activity... 2746 info.thumbnail = createThumbnailBitmap(r); 2747 info.description = r.activity.onCreateDescription(); 2748 } catch (Exception e) { 2749 if (!mInstrumentation.onException(r.activity, e)) { 2750 throw new RuntimeException( 2751 "Unable to save state of activity " 2752 + r.intent.getComponent().toShortString() 2753 + ": " + e.toString(), e); 2754 } 2755 } 2756 } 2757 2758 // Next have the activity save its current state and managed dialogs... 2759 if (!r.activity.mFinished && saveState) { 2760 if (r.state == null) { 2761 state = new Bundle(); 2762 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state); 2763 r.state = state; 2764 } else { 2765 state = r.state; 2766 } 2767 } 2768 2769 if (!keepShown) { 2770 try { 2771 // Now we are idle. 2772 r.activity.performStop(); 2773 } catch (Exception e) { 2774 if (!mInstrumentation.onException(r.activity, e)) { 2775 throw new RuntimeException( 2776 "Unable to stop activity " 2777 + r.intent.getComponent().toShortString() 2778 + ": " + e.toString(), e); 2779 } 2780 } 2781 r.stopped = true; 2782 } 2783 2784 r.paused = true; 2785 } 2786 } 2787 2788 private void updateVisibility(ActivityClientRecord r, boolean show) { 2789 View v = r.activity.mDecor; 2790 if (v != null) { 2791 if (show) { 2792 if (!r.activity.mVisibleFromServer) { 2793 r.activity.mVisibleFromServer = true; 2794 mNumVisibleActivities++; 2795 if (r.activity.mVisibleFromClient) { 2796 r.activity.makeVisible(); 2797 } 2798 } 2799 if (r.newConfig != null) { 2800 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis " 2801 + r.activityInfo.name + " with new config " + r.newConfig); 2802 performConfigurationChanged(r.activity, r.newConfig); 2803 r.newConfig = null; 2804 } 2805 } else { 2806 if (r.activity.mVisibleFromServer) { 2807 r.activity.mVisibleFromServer = false; 2808 mNumVisibleActivities--; 2809 v.setVisibility(View.INVISIBLE); 2810 } 2811 } 2812 } 2813 } 2814 2815 private void handleStopActivity(IBinder token, boolean show, int configChanges) { 2816 ActivityClientRecord r = mActivities.get(token); 2817 r.activity.mConfigChangeFlags |= configChanges; 2818 2819 StopInfo info = new StopInfo(); 2820 performStopActivityInner(r, info, show, true); 2821 2822 if (localLOGV) Slog.v( 2823 TAG, "Finishing stop of " + r + ": show=" + show 2824 + " win=" + r.window); 2825 2826 updateVisibility(r, show); 2827 2828 // Make sure any pending writes are now committed. 2829 if (!r.isPreHoneycomb()) { 2830 QueuedWork.waitToFinish(); 2831 } 2832 2833 // Tell activity manager we have been stopped. 2834 try { 2835 ActivityManagerNative.getDefault().activityStopped( 2836 r.token, r.state, info.thumbnail, info.description); 2837 } catch (RemoteException ex) { 2838 } 2839 } 2840 2841 final void performRestartActivity(IBinder token) { 2842 ActivityClientRecord r = mActivities.get(token); 2843 if (r.stopped) { 2844 r.activity.performRestart(); 2845 r.stopped = false; 2846 } 2847 } 2848 2849 private void handleWindowVisibility(IBinder token, boolean show) { 2850 ActivityClientRecord r = mActivities.get(token); 2851 2852 if (r == null) { 2853 Log.w(TAG, "handleWindowVisibility: no activity for token " + token); 2854 return; 2855 } 2856 2857 if (!show && !r.stopped) { 2858 performStopActivityInner(r, null, show, false); 2859 } else if (show && r.stopped) { 2860 // If we are getting ready to gc after going to the background, well 2861 // we are back active so skip it. 2862 unscheduleGcIdler(); 2863 2864 r.activity.performRestart(); 2865 r.stopped = false; 2866 } 2867 if (r.activity.mDecor != null) { 2868 if (false) Slog.v( 2869 TAG, "Handle window " + r + " visibility: " + show); 2870 updateVisibility(r, show); 2871 } 2872 } 2873 2874 private void handleSleeping(IBinder token, boolean sleeping) { 2875 ActivityClientRecord r = mActivities.get(token); 2876 2877 if (r == null) { 2878 Log.w(TAG, "handleSleeping: no activity for token " + token); 2879 return; 2880 } 2881 2882 if (sleeping) { 2883 if (!r.stopped && !r.isPreHoneycomb()) { 2884 try { 2885 // Now we are idle. 2886 r.activity.performStop(); 2887 } catch (Exception e) { 2888 if (!mInstrumentation.onException(r.activity, e)) { 2889 throw new RuntimeException( 2890 "Unable to stop activity " 2891 + r.intent.getComponent().toShortString() 2892 + ": " + e.toString(), e); 2893 } 2894 } 2895 r.stopped = true; 2896 } 2897 2898 // Make sure any pending writes are now committed. 2899 if (!r.isPreHoneycomb()) { 2900 QueuedWork.waitToFinish(); 2901 } 2902 2903 // Tell activity manager we slept. 2904 try { 2905 ActivityManagerNative.getDefault().activitySlept(r.token); 2906 } catch (RemoteException ex) { 2907 } 2908 } else { 2909 if (r.stopped && r.activity.mVisibleFromServer) { 2910 r.activity.performRestart(); 2911 r.stopped = false; 2912 } 2913 } 2914 } 2915 2916 private void handleSetCoreSettings(Bundle coreSettings) { 2917 synchronized (mPackages) { 2918 mCoreSettings = coreSettings; 2919 } 2920 } 2921 2922 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) { 2923 LoadedApk apk = peekPackageInfo(data.pkg, false); 2924 if (apk != null) { 2925 apk.mCompatibilityInfo.set(data.info); 2926 } 2927 apk = peekPackageInfo(data.pkg, true); 2928 if (apk != null) { 2929 apk.mCompatibilityInfo.set(data.info); 2930 } 2931 handleConfigurationChanged(mConfiguration, data.info); 2932 WindowManagerImpl.getDefault().reportNewConfiguration(mConfiguration); 2933 } 2934 2935 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) { 2936 final int N = results.size(); 2937 for (int i=0; i<N; i++) { 2938 ResultInfo ri = results.get(i); 2939 try { 2940 if (ri.mData != null) { 2941 ri.mData.setExtrasClassLoader(r.activity.getClassLoader()); 2942 } 2943 if (DEBUG_RESULTS) Slog.v(TAG, 2944 "Delivering result to activity " + r + " : " + ri); 2945 r.activity.dispatchActivityResult(ri.mResultWho, 2946 ri.mRequestCode, ri.mResultCode, ri.mData); 2947 } catch (Exception e) { 2948 if (!mInstrumentation.onException(r.activity, e)) { 2949 throw new RuntimeException( 2950 "Failure delivering result " + ri + " to activity " 2951 + r.intent.getComponent().toShortString() 2952 + ": " + e.toString(), e); 2953 } 2954 } 2955 } 2956 } 2957 2958 private void handleSendResult(ResultData res) { 2959 ActivityClientRecord r = mActivities.get(res.token); 2960 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r); 2961 if (r != null) { 2962 final boolean resumed = !r.paused; 2963 if (!r.activity.mFinished && r.activity.mDecor != null 2964 && r.hideForNow && resumed) { 2965 // We had hidden the activity because it started another 2966 // one... we have gotten a result back and we are not 2967 // paused, so make sure our window is visible. 2968 updateVisibility(r, true); 2969 } 2970 if (resumed) { 2971 try { 2972 // Now we are idle. 2973 r.activity.mCalled = false; 2974 r.activity.mTemporaryPause = true; 2975 mInstrumentation.callActivityOnPause(r.activity); 2976 if (!r.activity.mCalled) { 2977 throw new SuperNotCalledException( 2978 "Activity " + r.intent.getComponent().toShortString() 2979 + " did not call through to super.onPause()"); 2980 } 2981 } catch (SuperNotCalledException e) { 2982 throw e; 2983 } catch (Exception e) { 2984 if (!mInstrumentation.onException(r.activity, e)) { 2985 throw new RuntimeException( 2986 "Unable to pause activity " 2987 + r.intent.getComponent().toShortString() 2988 + ": " + e.toString(), e); 2989 } 2990 } 2991 } 2992 deliverResults(r, res.results); 2993 if (resumed) { 2994 r.activity.performResume(); 2995 r.activity.mTemporaryPause = false; 2996 } 2997 } 2998 } 2999 3000 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) { 3001 return performDestroyActivity(token, finishing, 0, false); 3002 } 3003 3004 private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing, 3005 int configChanges, boolean getNonConfigInstance) { 3006 ActivityClientRecord r = mActivities.get(token); 3007 Class activityClass = null; 3008 if (localLOGV) Slog.v(TAG, "Performing finish of " + r); 3009 if (r != null) { 3010 activityClass = r.activity.getClass(); 3011 r.activity.mConfigChangeFlags |= configChanges; 3012 if (finishing) { 3013 r.activity.mFinished = true; 3014 } 3015 if (!r.paused) { 3016 try { 3017 r.activity.mCalled = false; 3018 mInstrumentation.callActivityOnPause(r.activity); 3019 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, 3020 r.activity.getComponentName().getClassName()); 3021 if (!r.activity.mCalled) { 3022 throw new SuperNotCalledException( 3023 "Activity " + safeToComponentShortString(r.intent) 3024 + " did not call through to super.onPause()"); 3025 } 3026 } catch (SuperNotCalledException e) { 3027 throw e; 3028 } catch (Exception e) { 3029 if (!mInstrumentation.onException(r.activity, e)) { 3030 throw new RuntimeException( 3031 "Unable to pause activity " 3032 + safeToComponentShortString(r.intent) 3033 + ": " + e.toString(), e); 3034 } 3035 } 3036 r.paused = true; 3037 } 3038 if (!r.stopped) { 3039 try { 3040 r.activity.performStop(); 3041 } catch (SuperNotCalledException e) { 3042 throw e; 3043 } catch (Exception e) { 3044 if (!mInstrumentation.onException(r.activity, e)) { 3045 throw new RuntimeException( 3046 "Unable to stop activity " 3047 + safeToComponentShortString(r.intent) 3048 + ": " + e.toString(), e); 3049 } 3050 } 3051 r.stopped = true; 3052 } 3053 if (getNonConfigInstance) { 3054 try { 3055 r.lastNonConfigurationInstances 3056 = r.activity.retainNonConfigurationInstances(); 3057 } catch (Exception e) { 3058 if (!mInstrumentation.onException(r.activity, e)) { 3059 throw new RuntimeException( 3060 "Unable to retain activity " 3061 + r.intent.getComponent().toShortString() 3062 + ": " + e.toString(), e); 3063 } 3064 } 3065 } 3066 try { 3067 r.activity.mCalled = false; 3068 mInstrumentation.callActivityOnDestroy(r.activity); 3069 if (!r.activity.mCalled) { 3070 throw new SuperNotCalledException( 3071 "Activity " + safeToComponentShortString(r.intent) + 3072 " did not call through to super.onDestroy()"); 3073 } 3074 if (r.window != null) { 3075 r.window.closeAllPanels(); 3076 } 3077 } catch (SuperNotCalledException e) { 3078 throw e; 3079 } catch (Exception e) { 3080 if (!mInstrumentation.onException(r.activity, e)) { 3081 throw new RuntimeException( 3082 "Unable to destroy activity " + safeToComponentShortString(r.intent) 3083 + ": " + e.toString(), e); 3084 } 3085 } 3086 } 3087 mActivities.remove(token); 3088 StrictMode.decrementExpectedActivityCount(activityClass); 3089 return r; 3090 } 3091 3092 private static String safeToComponentShortString(Intent intent) { 3093 ComponentName component = intent.getComponent(); 3094 return component == null ? "[Unknown]" : component.toShortString(); 3095 } 3096 3097 private void handleDestroyActivity(IBinder token, boolean finishing, 3098 int configChanges, boolean getNonConfigInstance) { 3099 ActivityClientRecord r = performDestroyActivity(token, finishing, 3100 configChanges, getNonConfigInstance); 3101 if (r != null) { 3102 cleanUpPendingRemoveWindows(r); 3103 WindowManager wm = r.activity.getWindowManager(); 3104 View v = r.activity.mDecor; 3105 if (v != null) { 3106 if (r.activity.mVisibleFromServer) { 3107 mNumVisibleActivities--; 3108 } 3109 IBinder wtoken = v.getWindowToken(); 3110 if (r.activity.mWindowAdded) { 3111 if (r.onlyLocalRequest) { 3112 // Hold off on removing this until the new activity's 3113 // window is being added. 3114 r.mPendingRemoveWindow = v; 3115 r.mPendingRemoveWindowManager = wm; 3116 } else { 3117 wm.removeViewImmediate(v); 3118 } 3119 } 3120 if (wtoken != null && r.mPendingRemoveWindow == null) { 3121 WindowManagerImpl.getDefault().closeAll(wtoken, 3122 r.activity.getClass().getName(), "Activity"); 3123 } 3124 r.activity.mDecor = null; 3125 } 3126 if (r.mPendingRemoveWindow == null) { 3127 // If we are delaying the removal of the activity window, then 3128 // we can't clean up all windows here. Note that we can't do 3129 // so later either, which means any windows that aren't closed 3130 // by the app will leak. Well we try to warning them a lot 3131 // about leaking windows, because that is a bug, so if they are 3132 // using this recreate facility then they get to live with leaks. 3133 WindowManagerImpl.getDefault().closeAll(token, 3134 r.activity.getClass().getName(), "Activity"); 3135 } 3136 3137 // Mocked out contexts won't be participating in the normal 3138 // process lifecycle, but if we're running with a proper 3139 // ApplicationContext we need to have it tear down things 3140 // cleanly. 3141 Context c = r.activity.getBaseContext(); 3142 if (c instanceof ContextImpl) { 3143 ((ContextImpl) c).scheduleFinalCleanup( 3144 r.activity.getClass().getName(), "Activity"); 3145 } 3146 } 3147 if (finishing) { 3148 try { 3149 ActivityManagerNative.getDefault().activityDestroyed(token); 3150 } catch (RemoteException ex) { 3151 // If the system process has died, it's game over for everyone. 3152 } 3153 } 3154 } 3155 3156 public final void requestRelaunchActivity(IBinder token, 3157 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents, 3158 int configChanges, boolean notResumed, Configuration config, 3159 boolean fromServer) { 3160 ActivityClientRecord target = null; 3161 3162 synchronized (mPackages) { 3163 for (int i=0; i<mRelaunchingActivities.size(); i++) { 3164 ActivityClientRecord r = mRelaunchingActivities.get(i); 3165 if (r.token == token) { 3166 target = r; 3167 if (pendingResults != null) { 3168 if (r.pendingResults != null) { 3169 r.pendingResults.addAll(pendingResults); 3170 } else { 3171 r.pendingResults = pendingResults; 3172 } 3173 } 3174 if (pendingNewIntents != null) { 3175 if (r.pendingIntents != null) { 3176 r.pendingIntents.addAll(pendingNewIntents); 3177 } else { 3178 r.pendingIntents = pendingNewIntents; 3179 } 3180 } 3181 break; 3182 } 3183 } 3184 3185 if (target == null) { 3186 target = new ActivityClientRecord(); 3187 target.token = token; 3188 target.pendingResults = pendingResults; 3189 target.pendingIntents = pendingNewIntents; 3190 if (!fromServer) { 3191 ActivityClientRecord existing = mActivities.get(token); 3192 if (existing != null) { 3193 target.startsNotResumed = existing.paused; 3194 } 3195 target.onlyLocalRequest = true; 3196 } 3197 mRelaunchingActivities.add(target); 3198 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target); 3199 } 3200 3201 if (fromServer) { 3202 target.startsNotResumed = notResumed; 3203 target.onlyLocalRequest = false; 3204 } 3205 if (config != null) { 3206 target.createdConfig = config; 3207 } 3208 target.pendingConfigChanges |= configChanges; 3209 } 3210 } 3211 3212 private void handleRelaunchActivity(ActivityClientRecord tmp) { 3213 // If we are getting ready to gc after going to the background, well 3214 // we are back active so skip it. 3215 unscheduleGcIdler(); 3216 3217 Configuration changedConfig = null; 3218 int configChanges = 0; 3219 3220 // First: make sure we have the most recent configuration and most 3221 // recent version of the activity, or skip it if some previous call 3222 // had taken a more recent version. 3223 synchronized (mPackages) { 3224 int N = mRelaunchingActivities.size(); 3225 IBinder token = tmp.token; 3226 tmp = null; 3227 for (int i=0; i<N; i++) { 3228 ActivityClientRecord r = mRelaunchingActivities.get(i); 3229 if (r.token == token) { 3230 tmp = r; 3231 configChanges |= tmp.pendingConfigChanges; 3232 mRelaunchingActivities.remove(i); 3233 i--; 3234 N--; 3235 } 3236 } 3237 3238 if (tmp == null) { 3239 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!"); 3240 return; 3241 } 3242 3243 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity " 3244 + tmp.token + " with configChanges=0x" 3245 + Integer.toHexString(configChanges)); 3246 3247 if (mPendingConfiguration != null) { 3248 changedConfig = mPendingConfiguration; 3249 mPendingConfiguration = null; 3250 } 3251 } 3252 3253 if (tmp.createdConfig != null) { 3254 // If the activity manager is passing us its current config, 3255 // assume that is really what we want regardless of what we 3256 // may have pending. 3257 if (mConfiguration == null 3258 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration) 3259 && mConfiguration.diff(tmp.createdConfig) != 0)) { 3260 if (changedConfig == null 3261 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) { 3262 changedConfig = tmp.createdConfig; 3263 } 3264 } 3265 } 3266 3267 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity " 3268 + tmp.token + ": changedConfig=" + changedConfig); 3269 3270 // If there was a pending configuration change, execute it first. 3271 if (changedConfig != null) { 3272 handleConfigurationChanged(changedConfig, null); 3273 } 3274 3275 ActivityClientRecord r = mActivities.get(tmp.token); 3276 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r); 3277 if (r == null) { 3278 return; 3279 } 3280 3281 r.activity.mConfigChangeFlags |= configChanges; 3282 r.onlyLocalRequest = tmp.onlyLocalRequest; 3283 Intent currentIntent = r.activity.mIntent; 3284 3285 r.activity.mChangingConfigurations = true; 3286 3287 // Need to ensure state is saved. 3288 if (!r.paused) { 3289 performPauseActivity(r.token, false, r.isPreHoneycomb()); 3290 } 3291 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) { 3292 r.state = new Bundle(); 3293 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state); 3294 } 3295 3296 handleDestroyActivity(r.token, false, configChanges, true); 3297 3298 r.activity = null; 3299 r.window = null; 3300 r.hideForNow = false; 3301 r.nextIdle = null; 3302 // Merge any pending results and pending intents; don't just replace them 3303 if (tmp.pendingResults != null) { 3304 if (r.pendingResults == null) { 3305 r.pendingResults = tmp.pendingResults; 3306 } else { 3307 r.pendingResults.addAll(tmp.pendingResults); 3308 } 3309 } 3310 if (tmp.pendingIntents != null) { 3311 if (r.pendingIntents == null) { 3312 r.pendingIntents = tmp.pendingIntents; 3313 } else { 3314 r.pendingIntents.addAll(tmp.pendingIntents); 3315 } 3316 } 3317 r.startsNotResumed = tmp.startsNotResumed; 3318 3319 handleLaunchActivity(r, currentIntent); 3320 } 3321 3322 private void handleRequestThumbnail(IBinder token) { 3323 ActivityClientRecord r = mActivities.get(token); 3324 Bitmap thumbnail = createThumbnailBitmap(r); 3325 CharSequence description = null; 3326 try { 3327 description = r.activity.onCreateDescription(); 3328 } catch (Exception e) { 3329 if (!mInstrumentation.onException(r.activity, e)) { 3330 throw new RuntimeException( 3331 "Unable to create description of activity " 3332 + r.intent.getComponent().toShortString() 3333 + ": " + e.toString(), e); 3334 } 3335 } 3336 //System.out.println("Reporting top thumbnail " + thumbnail); 3337 try { 3338 ActivityManagerNative.getDefault().reportThumbnail( 3339 token, thumbnail, description); 3340 } catch (RemoteException ex) { 3341 } 3342 } 3343 3344 ArrayList<ComponentCallbacks2> collectComponentCallbacksLocked( 3345 boolean allActivities, Configuration newConfig) { 3346 ArrayList<ComponentCallbacks2> callbacks 3347 = new ArrayList<ComponentCallbacks2>(); 3348 3349 if (mActivities.size() > 0) { 3350 Iterator<ActivityClientRecord> it = mActivities.values().iterator(); 3351 while (it.hasNext()) { 3352 ActivityClientRecord ar = it.next(); 3353 Activity a = ar.activity; 3354 if (a != null) { 3355 Configuration thisConfig = applyConfigCompatMainThread(newConfig, 3356 ar.packageInfo.mCompatibilityInfo.getIfNeeded()); 3357 if (!ar.activity.mFinished && (allActivities || 3358 (a != null && !ar.paused))) { 3359 // If the activity is currently resumed, its configuration 3360 // needs to change right now. 3361 callbacks.add(a); 3362 } else if (thisConfig != null) { 3363 // Otherwise, we will tell it about the change 3364 // the next time it is resumed or shown. Note that 3365 // the activity manager may, before then, decide the 3366 // activity needs to be destroyed to handle its new 3367 // configuration. 3368 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity " 3369 + ar.activityInfo.name + " newConfig=" + thisConfig); 3370 ar.newConfig = thisConfig; 3371 } 3372 } 3373 } 3374 } 3375 if (mServices.size() > 0) { 3376 Iterator<Service> it = mServices.values().iterator(); 3377 while (it.hasNext()) { 3378 callbacks.add(it.next()); 3379 } 3380 } 3381 synchronized (mProviderMap) { 3382 if (mLocalProviders.size() > 0) { 3383 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator(); 3384 while (it.hasNext()) { 3385 callbacks.add(it.next().mLocalProvider); 3386 } 3387 } 3388 } 3389 final int N = mAllApplications.size(); 3390 for (int i=0; i<N; i++) { 3391 callbacks.add(mAllApplications.get(i)); 3392 } 3393 3394 return callbacks; 3395 } 3396 3397 private final void performConfigurationChanged( 3398 ComponentCallbacks2 cb, Configuration config) { 3399 // Only for Activity objects, check that they actually call up to their 3400 // superclass implementation. ComponentCallbacks2 is an interface, so 3401 // we check the runtime type and act accordingly. 3402 Activity activity = (cb instanceof Activity) ? (Activity) cb : null; 3403 if (activity != null) { 3404 activity.mCalled = false; 3405 } 3406 3407 boolean shouldChangeConfig = false; 3408 if ((activity == null) || (activity.mCurrentConfig == null)) { 3409 shouldChangeConfig = true; 3410 } else { 3411 3412 // If the new config is the same as the config this Activity 3413 // is already running with then don't bother calling 3414 // onConfigurationChanged 3415 int diff = activity.mCurrentConfig.diff(config); 3416 if (diff != 0) { 3417 // If this activity doesn't handle any of the config changes 3418 // then don't bother calling onConfigurationChanged as we're 3419 // going to destroy it. 3420 if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) { 3421 shouldChangeConfig = true; 3422 } 3423 } 3424 } 3425 3426 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb 3427 + ": shouldChangeConfig=" + shouldChangeConfig); 3428 if (shouldChangeConfig) { 3429 cb.onConfigurationChanged(config); 3430 3431 if (activity != null) { 3432 if (!activity.mCalled) { 3433 throw new SuperNotCalledException( 3434 "Activity " + activity.getLocalClassName() + 3435 " did not call through to super.onConfigurationChanged()"); 3436 } 3437 activity.mConfigChangeFlags = 0; 3438 activity.mCurrentConfig = new Configuration(config); 3439 } 3440 } 3441 } 3442 3443 public final void applyConfigurationToResources(Configuration config) { 3444 synchronized (mPackages) { 3445 applyConfigurationToResourcesLocked(config, null); 3446 } 3447 } 3448 3449 final boolean applyConfigurationToResourcesLocked(Configuration config, 3450 CompatibilityInfo compat) { 3451 if (mResConfiguration == null) { 3452 mResConfiguration = new Configuration(); 3453 } 3454 if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) { 3455 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq=" 3456 + mResConfiguration.seq + ", newSeq=" + config.seq); 3457 return false; 3458 } 3459 int changes = mResConfiguration.updateFrom(config); 3460 DisplayMetrics dm = getDisplayMetricsLocked(compat, true); 3461 3462 if (compat != null && (mResCompatibilityInfo == null || 3463 !mResCompatibilityInfo.equals(compat))) { 3464 mResCompatibilityInfo = compat; 3465 changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT 3466 | ActivityInfo.CONFIG_SCREEN_SIZE 3467 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE; 3468 } 3469 3470 // set it for java, this also affects newly created Resources 3471 if (config.locale != null) { 3472 Locale.setDefault(config.locale); 3473 } 3474 3475 Resources.updateSystemConfiguration(config, dm, compat); 3476 3477 ApplicationPackageManager.configurationChanged(); 3478 //Slog.i(TAG, "Configuration changed in " + currentPackageName()); 3479 3480 Iterator<WeakReference<Resources>> it = 3481 mActiveResources.values().iterator(); 3482 //Iterator<Map.Entry<String, WeakReference<Resources>>> it = 3483 // mActiveResources.entrySet().iterator(); 3484 while (it.hasNext()) { 3485 WeakReference<Resources> v = it.next(); 3486 Resources r = v.get(); 3487 if (r != null) { 3488 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources " 3489 + r + " config to: " + config); 3490 r.updateConfiguration(config, dm, compat); 3491 //Slog.i(TAG, "Updated app resources " + v.getKey() 3492 // + " " + r + ": " + r.getConfiguration()); 3493 } else { 3494 //Slog.i(TAG, "Removing old resources " + v.getKey()); 3495 it.remove(); 3496 } 3497 } 3498 3499 return changes != 0; 3500 } 3501 3502 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) { 3503 3504 ArrayList<ComponentCallbacks2> callbacks = null; 3505 3506 synchronized (mPackages) { 3507 if (mPendingConfiguration != null) { 3508 if (!mPendingConfiguration.isOtherSeqNewer(config)) { 3509 config = mPendingConfiguration; 3510 } 3511 mPendingConfiguration = null; 3512 } 3513 3514 if (config == null) { 3515 return; 3516 } 3517 3518 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: " 3519 + config); 3520 3521 applyConfigurationToResourcesLocked(config, compat); 3522 3523 if (mConfiguration == null) { 3524 mConfiguration = new Configuration(); 3525 } 3526 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) { 3527 return; 3528 } 3529 mConfiguration.updateFrom(config); 3530 if (mCompatConfiguration == null) { 3531 mCompatConfiguration = new Configuration(); 3532 } 3533 mCompatConfiguration.setTo(mConfiguration); 3534 if (mResCompatibilityInfo != null && !mResCompatibilityInfo.supportsScreen()) { 3535 mResCompatibilityInfo.applyToConfiguration(mCompatConfiguration); 3536 config = mCompatConfiguration; 3537 } 3538 callbacks = collectComponentCallbacksLocked(false, config); 3539 } 3540 3541 // Cleanup hardware accelerated stuff 3542 WindowManagerImpl.getDefault().trimLocalMemory(); 3543 3544 if (callbacks != null) { 3545 final int N = callbacks.size(); 3546 for (int i=0; i<N; i++) { 3547 performConfigurationChanged(callbacks.get(i), config); 3548 } 3549 } 3550 } 3551 3552 final void handleActivityConfigurationChanged(IBinder token) { 3553 ActivityClientRecord r = mActivities.get(token); 3554 if (r == null || r.activity == null) { 3555 return; 3556 } 3557 3558 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: " 3559 + r.activityInfo.name); 3560 3561 performConfigurationChanged(r.activity, mCompatConfiguration); 3562 } 3563 3564 final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) { 3565 if (start) { 3566 try { 3567 switch (profileType) { 3568 case 1: 3569 ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor()); 3570 break; 3571 default: 3572 mBoundApplication.setProfiler(pcd.path, pcd.fd); 3573 mBoundApplication.autoStopProfiler = false; 3574 mBoundApplication.startProfiling(); 3575 break; 3576 } 3577 } catch (RuntimeException e) { 3578 Slog.w(TAG, "Profiling failed on path " + pcd.path 3579 + " -- can the process access this path?"); 3580 } finally { 3581 try { 3582 pcd.fd.close(); 3583 } catch (IOException e) { 3584 Slog.w(TAG, "Failure closing profile fd", e); 3585 } 3586 } 3587 } else { 3588 switch (profileType) { 3589 case 1: 3590 ViewDebug.stopLooperProfiling(); 3591 break; 3592 default: 3593 mBoundApplication.stopProfiling(); 3594 break; 3595 } 3596 } 3597 } 3598 3599 final void handleDumpHeap(boolean managed, DumpHeapData dhd) { 3600 if (managed) { 3601 try { 3602 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor()); 3603 } catch (IOException e) { 3604 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path 3605 + " -- can the process access this path?"); 3606 } finally { 3607 try { 3608 dhd.fd.close(); 3609 } catch (IOException e) { 3610 Slog.w(TAG, "Failure closing profile fd", e); 3611 } 3612 } 3613 } else { 3614 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor()); 3615 } 3616 } 3617 3618 final void handleDispatchPackageBroadcast(int cmd, String[] packages) { 3619 boolean hasPkgInfo = false; 3620 if (packages != null) { 3621 for (int i=packages.length-1; i>=0; i--) { 3622 //Slog.i(TAG, "Cleaning old package: " + packages[i]); 3623 if (!hasPkgInfo) { 3624 WeakReference<LoadedApk> ref; 3625 ref = mPackages.get(packages[i]); 3626 if (ref != null && ref.get() != null) { 3627 hasPkgInfo = true; 3628 } else { 3629 ref = mResourcePackages.get(packages[i]); 3630 if (ref != null && ref.get() != null) { 3631 hasPkgInfo = true; 3632 } 3633 } 3634 } 3635 mPackages.remove(packages[i]); 3636 mResourcePackages.remove(packages[i]); 3637 } 3638 } 3639 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, 3640 hasPkgInfo); 3641 } 3642 3643 final void handleLowMemory() { 3644 ArrayList<ComponentCallbacks2> callbacks; 3645 3646 synchronized (mPackages) { 3647 callbacks = collectComponentCallbacksLocked(true, null); 3648 } 3649 3650 final int N = callbacks.size(); 3651 for (int i=0; i<N; i++) { 3652 callbacks.get(i).onLowMemory(); 3653 } 3654 3655 // Ask SQLite to free up as much memory as it can, mostly from its page caches. 3656 if (Process.myUid() != Process.SYSTEM_UID) { 3657 int sqliteReleased = SQLiteDatabase.releaseMemory(); 3658 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased); 3659 } 3660 3661 // Ask graphics to free up as much as possible (font/image caches) 3662 Canvas.freeCaches(); 3663 3664 BinderInternal.forceGc("mem"); 3665 } 3666 3667 final void handleTrimMemory(int level) { 3668 WindowManagerImpl.getDefault().trimMemory(level); 3669 ArrayList<ComponentCallbacks2> callbacks; 3670 3671 synchronized (mPackages) { 3672 callbacks = collectComponentCallbacksLocked(true, null); 3673 } 3674 3675 final int N = callbacks.size(); 3676 for (int i=0; i<N; i++) { 3677 callbacks.get(i).onTrimMemory(level); 3678 } 3679 } 3680 3681 private void handleBindApplication(AppBindData data) { 3682 mBoundApplication = data; 3683 mConfiguration = new Configuration(data.config); 3684 mCompatConfiguration = new Configuration(data.config); 3685 3686 // send up app name; do this *before* waiting for debugger 3687 Process.setArgV0(data.processName); 3688 android.ddm.DdmHandleAppName.setAppName(data.processName); 3689 3690 if (data.profileFd != null) { 3691 data.startProfiling(); 3692 } 3693 3694 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask 3695 // implementation to use the pool executor. Normally, we use the 3696 // serialized executor as the default. This has to happen in the 3697 // main thread so the main looper is set right. 3698 if (data.appInfo.targetSdkVersion <= 12) { 3699 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 3700 } 3701 3702 /* 3703 * Before spawning a new process, reset the time zone to be the system time zone. 3704 * This needs to be done because the system time zone could have changed after the 3705 * the spawning of this process. Without doing this this process would have the incorrect 3706 * system time zone. 3707 */ 3708 TimeZone.setDefault(null); 3709 3710 /* 3711 * Initialize the default locale in this process for the reasons we set the time zone. 3712 */ 3713 Locale.setDefault(data.config.locale); 3714 3715 /* 3716 * Update the system configuration since its preloaded and might not 3717 * reflect configuration changes. The configuration object passed 3718 * in AppBindData can be safely assumed to be up to date 3719 */ 3720 applyConfigurationToResourcesLocked(data.config, data.compatInfo); 3721 3722 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo); 3723 3724 /** 3725 * For system applications on userdebug/eng builds, log stack 3726 * traces of disk and network access to dropbox for analysis. 3727 */ 3728 if ((data.appInfo.flags & 3729 (ApplicationInfo.FLAG_SYSTEM | 3730 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) { 3731 StrictMode.conditionallyEnableDebugLogging(); 3732 } 3733 3734 /** 3735 * For apps targetting SDK Honeycomb or later, we don't allow 3736 * network usage on the main event loop / UI thread. 3737 * 3738 * Note to those grepping: this is what ultimately throws 3739 * NetworkOnMainThreadException ... 3740 */ 3741 if (data.appInfo.targetSdkVersion > 9) { 3742 StrictMode.enableDeathOnNetwork(); 3743 } 3744 3745 /** 3746 * Switch this process to density compatibility mode if needed. 3747 */ 3748 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) 3749 == 0) { 3750 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT); 3751 } 3752 3753 if (data.debugMode != IApplicationThread.DEBUG_OFF) { 3754 // XXX should have option to change the port. 3755 Debug.changeDebugPort(8100); 3756 if (data.debugMode == IApplicationThread.DEBUG_WAIT) { 3757 Slog.w(TAG, "Application " + data.info.getPackageName() 3758 + " is waiting for the debugger on port 8100..."); 3759 3760 IActivityManager mgr = ActivityManagerNative.getDefault(); 3761 try { 3762 mgr.showWaitingForDebugger(mAppThread, true); 3763 } catch (RemoteException ex) { 3764 } 3765 3766 Debug.waitForDebugger(); 3767 3768 try { 3769 mgr.showWaitingForDebugger(mAppThread, false); 3770 } catch (RemoteException ex) { 3771 } 3772 3773 } else { 3774 Slog.w(TAG, "Application " + data.info.getPackageName() 3775 + " can be debugged on port 8100..."); 3776 } 3777 } 3778 3779 /** 3780 * Initialize the default http proxy in this process for the reasons we set the time zone. 3781 */ 3782 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE); 3783 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b); 3784 try { 3785 ProxyProperties proxyProperties = service.getProxy(); 3786 Proxy.setHttpProxySystemProperty(proxyProperties); 3787 } catch (RemoteException e) {} 3788 3789 if (data.instrumentationName != null) { 3790 ContextImpl appContext = new ContextImpl(); 3791 appContext.init(data.info, null, this); 3792 InstrumentationInfo ii = null; 3793 try { 3794 ii = appContext.getPackageManager(). 3795 getInstrumentationInfo(data.instrumentationName, 0); 3796 } catch (PackageManager.NameNotFoundException e) { 3797 } 3798 if (ii == null) { 3799 throw new RuntimeException( 3800 "Unable to find instrumentation info for: " 3801 + data.instrumentationName); 3802 } 3803 3804 mInstrumentationAppDir = ii.sourceDir; 3805 mInstrumentationAppPackage = ii.packageName; 3806 mInstrumentedAppDir = data.info.getAppDir(); 3807 3808 ApplicationInfo instrApp = new ApplicationInfo(); 3809 instrApp.packageName = ii.packageName; 3810 instrApp.sourceDir = ii.sourceDir; 3811 instrApp.publicSourceDir = ii.publicSourceDir; 3812 instrApp.dataDir = ii.dataDir; 3813 instrApp.nativeLibraryDir = ii.nativeLibraryDir; 3814 LoadedApk pi = getPackageInfo(instrApp, data.compatInfo, 3815 appContext.getClassLoader(), false, true); 3816 ContextImpl instrContext = new ContextImpl(); 3817 instrContext.init(pi, null, this); 3818 3819 try { 3820 java.lang.ClassLoader cl = instrContext.getClassLoader(); 3821 mInstrumentation = (Instrumentation) 3822 cl.loadClass(data.instrumentationName.getClassName()).newInstance(); 3823 } catch (Exception e) { 3824 throw new RuntimeException( 3825 "Unable to instantiate instrumentation " 3826 + data.instrumentationName + ": " + e.toString(), e); 3827 } 3828 3829 mInstrumentation.init(this, instrContext, appContext, 3830 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher); 3831 3832 if (data.profileFile != null && !ii.handleProfiling 3833 && data.profileFd == null) { 3834 data.handlingProfiling = true; 3835 File file = new File(data.profileFile); 3836 file.getParentFile().mkdirs(); 3837 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024); 3838 } 3839 3840 try { 3841 mInstrumentation.onCreate(data.instrumentationArgs); 3842 } 3843 catch (Exception e) { 3844 throw new RuntimeException( 3845 "Exception thrown in onCreate() of " 3846 + data.instrumentationName + ": " + e.toString(), e); 3847 } 3848 3849 } else { 3850 mInstrumentation = new Instrumentation(); 3851 } 3852 3853 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) { 3854 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit(); 3855 } 3856 3857 // If the app is being launched for full backup or restore, bring it up in 3858 // a restricted environment with the base application class. 3859 Application app = data.info.makeApplication(data.restrictedBackupMode, null); 3860 mInitialApplication = app; 3861 3862 // don't bring up providers in restricted mode; they may depend on the 3863 // app's custom Application class 3864 if (!data.restrictedBackupMode){ 3865 List<ProviderInfo> providers = data.providers; 3866 if (providers != null) { 3867 installContentProviders(app, providers); 3868 // For process that contains content providers, we want to 3869 // ensure that the JIT is enabled "at some point". 3870 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000); 3871 } 3872 } 3873 3874 try { 3875 mInstrumentation.callApplicationOnCreate(app); 3876 } catch (Exception e) { 3877 if (!mInstrumentation.onException(app, e)) { 3878 throw new RuntimeException( 3879 "Unable to create application " + app.getClass().getName() 3880 + ": " + e.toString(), e); 3881 } 3882 } 3883 } 3884 3885 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) { 3886 IActivityManager am = ActivityManagerNative.getDefault(); 3887 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling 3888 && mBoundApplication.profileFd == null) { 3889 Debug.stopMethodTracing(); 3890 } 3891 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault() 3892 // + ", app thr: " + mAppThread); 3893 try { 3894 am.finishInstrumentation(mAppThread, resultCode, results); 3895 } catch (RemoteException ex) { 3896 } 3897 } 3898 3899 private void installContentProviders( 3900 Context context, List<ProviderInfo> providers) { 3901 final ArrayList<IActivityManager.ContentProviderHolder> results = 3902 new ArrayList<IActivityManager.ContentProviderHolder>(); 3903 3904 Iterator<ProviderInfo> i = providers.iterator(); 3905 while (i.hasNext()) { 3906 ProviderInfo cpi = i.next(); 3907 StringBuilder buf = new StringBuilder(128); 3908 buf.append("Pub "); 3909 buf.append(cpi.authority); 3910 buf.append(": "); 3911 buf.append(cpi.name); 3912 Log.i(TAG, buf.toString()); 3913 IContentProvider cp = installProvider(context, null, cpi, false); 3914 if (cp != null) { 3915 IActivityManager.ContentProviderHolder cph = 3916 new IActivityManager.ContentProviderHolder(cpi); 3917 cph.provider = cp; 3918 results.add(cph); 3919 // Don't ever unload this provider from the process. 3920 synchronized(mProviderMap) { 3921 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000)); 3922 } 3923 } 3924 } 3925 3926 try { 3927 ActivityManagerNative.getDefault().publishContentProviders( 3928 getApplicationThread(), results); 3929 } catch (RemoteException ex) { 3930 } 3931 } 3932 3933 private IContentProvider getExistingProvider(Context context, String name) { 3934 synchronized(mProviderMap) { 3935 final ProviderClientRecord pr = mProviderMap.get(name); 3936 if (pr != null) { 3937 return pr.mProvider; 3938 } 3939 return null; 3940 } 3941 } 3942 3943 private IContentProvider getProvider(Context context, String name) { 3944 IContentProvider existing = getExistingProvider(context, name); 3945 if (existing != null) { 3946 return existing; 3947 } 3948 3949 IActivityManager.ContentProviderHolder holder = null; 3950 try { 3951 holder = ActivityManagerNative.getDefault().getContentProvider( 3952 getApplicationThread(), name); 3953 } catch (RemoteException ex) { 3954 } 3955 if (holder == null) { 3956 Slog.e(TAG, "Failed to find provider info for " + name); 3957 return null; 3958 } 3959 3960 IContentProvider prov = installProvider(context, holder.provider, 3961 holder.info, true); 3962 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded); 3963 if (holder.noReleaseNeeded || holder.provider == null) { 3964 // We are not going to release the provider if it is an external 3965 // provider that doesn't care about being released, or if it is 3966 // a local provider running in this process. 3967 //Slog.i(TAG, "*** NO RELEASE NEEDED"); 3968 synchronized(mProviderMap) { 3969 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000)); 3970 } 3971 } 3972 return prov; 3973 } 3974 3975 public final IContentProvider acquireProvider(Context c, String name) { 3976 IContentProvider provider = getProvider(c, name); 3977 if(provider == null) 3978 return null; 3979 IBinder jBinder = provider.asBinder(); 3980 synchronized(mProviderMap) { 3981 ProviderRefCount prc = mProviderRefCountMap.get(jBinder); 3982 if(prc == null) { 3983 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1)); 3984 } else { 3985 prc.count++; 3986 } //end else 3987 } //end synchronized 3988 return provider; 3989 } 3990 3991 public final IContentProvider acquireExistingProvider(Context c, String name) { 3992 IContentProvider provider = getExistingProvider(c, name); 3993 if(provider == null) 3994 return null; 3995 IBinder jBinder = provider.asBinder(); 3996 synchronized(mProviderMap) { 3997 ProviderRefCount prc = mProviderRefCountMap.get(jBinder); 3998 if(prc == null) { 3999 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1)); 4000 } else { 4001 prc.count++; 4002 } //end else 4003 } //end synchronized 4004 return provider; 4005 } 4006 4007 public final boolean releaseProvider(IContentProvider provider) { 4008 if(provider == null) { 4009 return false; 4010 } 4011 IBinder jBinder = provider.asBinder(); 4012 synchronized(mProviderMap) { 4013 ProviderRefCount prc = mProviderRefCountMap.get(jBinder); 4014 if(prc == null) { 4015 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here"); 4016 return false; 4017 } else { 4018 prc.count--; 4019 if(prc.count == 0) { 4020 // Schedule the actual remove asynchronously, since we 4021 // don't know the context this will be called in. 4022 // TODO: it would be nice to post a delayed message, so 4023 // if we come back and need the same provider quickly 4024 // we will still have it available. 4025 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider); 4026 mH.sendMessage(msg); 4027 } //end if 4028 } //end else 4029 } //end synchronized 4030 return true; 4031 } 4032 4033 final void completeRemoveProvider(IContentProvider provider) { 4034 IBinder jBinder = provider.asBinder(); 4035 String name = null; 4036 synchronized(mProviderMap) { 4037 ProviderRefCount prc = mProviderRefCountMap.get(jBinder); 4038 if(prc != null && prc.count == 0) { 4039 mProviderRefCountMap.remove(jBinder); 4040 //invoke removeProvider to dereference provider 4041 name = removeProviderLocked(provider); 4042 } 4043 } 4044 4045 if (name != null) { 4046 try { 4047 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " + 4048 "ActivityManagerNative.removeContentProvider(" + name); 4049 ActivityManagerNative.getDefault().removeContentProvider( 4050 getApplicationThread(), name); 4051 } catch (RemoteException e) { 4052 //do nothing content provider object is dead any way 4053 } //end catch 4054 } 4055 } 4056 4057 public final String removeProviderLocked(IContentProvider provider) { 4058 if (provider == null) { 4059 return null; 4060 } 4061 IBinder providerBinder = provider.asBinder(); 4062 4063 String name = null; 4064 4065 // remove the provider from mProviderMap 4066 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator(); 4067 while (iter.hasNext()) { 4068 ProviderClientRecord pr = iter.next(); 4069 IBinder myBinder = pr.mProvider.asBinder(); 4070 if (myBinder == providerBinder) { 4071 //find if its published by this process itself 4072 if(pr.mLocalProvider != null) { 4073 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning"); 4074 return name; 4075 } 4076 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " + 4077 "death recipient"); 4078 //content provider is in another process 4079 myBinder.unlinkToDeath(pr, 0); 4080 iter.remove(); 4081 //invoke remove only once for the very first name seen 4082 if(name == null) { 4083 name = pr.mName; 4084 } 4085 } //end if myBinder 4086 } //end while iter 4087 4088 return name; 4089 } 4090 4091 final void removeDeadProvider(String name, IContentProvider provider) { 4092 synchronized(mProviderMap) { 4093 ProviderClientRecord pr = mProviderMap.get(name); 4094 if (pr.mProvider.asBinder() == provider.asBinder()) { 4095 Slog.i(TAG, "Removing dead content provider: " + name); 4096 ProviderClientRecord removed = mProviderMap.remove(name); 4097 if (removed != null) { 4098 removed.mProvider.asBinder().unlinkToDeath(removed, 0); 4099 } 4100 } 4101 } 4102 } 4103 4104 final void removeDeadProviderLocked(String name, IContentProvider provider) { 4105 ProviderClientRecord pr = mProviderMap.get(name); 4106 if (pr.mProvider.asBinder() == provider.asBinder()) { 4107 Slog.i(TAG, "Removing dead content provider: " + name); 4108 ProviderClientRecord removed = mProviderMap.remove(name); 4109 if (removed != null) { 4110 removed.mProvider.asBinder().unlinkToDeath(removed, 0); 4111 } 4112 } 4113 } 4114 4115 private IContentProvider installProvider(Context context, 4116 IContentProvider provider, ProviderInfo info, boolean noisy) { 4117 ContentProvider localProvider = null; 4118 if (provider == null) { 4119 if (noisy) { 4120 Slog.d(TAG, "Loading provider " + info.authority + ": " 4121 + info.name); 4122 } 4123 Context c = null; 4124 ApplicationInfo ai = info.applicationInfo; 4125 if (context.getPackageName().equals(ai.packageName)) { 4126 c = context; 4127 } else if (mInitialApplication != null && 4128 mInitialApplication.getPackageName().equals(ai.packageName)) { 4129 c = mInitialApplication; 4130 } else { 4131 try { 4132 c = context.createPackageContext(ai.packageName, 4133 Context.CONTEXT_INCLUDE_CODE); 4134 } catch (PackageManager.NameNotFoundException e) { 4135 // Ignore 4136 } 4137 } 4138 if (c == null) { 4139 Slog.w(TAG, "Unable to get context for package " + 4140 ai.packageName + 4141 " while loading content provider " + 4142 info.name); 4143 return null; 4144 } 4145 try { 4146 final java.lang.ClassLoader cl = c.getClassLoader(); 4147 localProvider = (ContentProvider)cl. 4148 loadClass(info.name).newInstance(); 4149 provider = localProvider.getIContentProvider(); 4150 if (provider == null) { 4151 Slog.e(TAG, "Failed to instantiate class " + 4152 info.name + " from sourceDir " + 4153 info.applicationInfo.sourceDir); 4154 return null; 4155 } 4156 if (false) Slog.v( 4157 TAG, "Instantiating local provider " + info.name); 4158 // XXX Need to create the correct context for this provider. 4159 localProvider.attachInfo(c, info); 4160 } catch (java.lang.Exception e) { 4161 if (!mInstrumentation.onException(null, e)) { 4162 throw new RuntimeException( 4163 "Unable to get provider " + info.name 4164 + ": " + e.toString(), e); 4165 } 4166 return null; 4167 } 4168 } else if (localLOGV) { 4169 Slog.v(TAG, "Installing external provider " + info.authority + ": " 4170 + info.name); 4171 } 4172 4173 synchronized (mProviderMap) { 4174 // Cache the pointer for the remote provider. 4175 String names[] = PATTERN_SEMICOLON.split(info.authority); 4176 for (int i=0; i<names.length; i++) { 4177 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider, 4178 localProvider); 4179 try { 4180 provider.asBinder().linkToDeath(pr, 0); 4181 mProviderMap.put(names[i], pr); 4182 } catch (RemoteException e) { 4183 return null; 4184 } 4185 } 4186 if (localProvider != null) { 4187 mLocalProviders.put(provider.asBinder(), 4188 new ProviderClientRecord(null, provider, localProvider)); 4189 } 4190 } 4191 4192 return provider; 4193 } 4194 4195 private void attach(boolean system) { 4196 sThreadLocal.set(this); 4197 mSystemThread = system; 4198 if (!system) { 4199 ViewRootImpl.addFirstDrawHandler(new Runnable() { 4200 public void run() { 4201 ensureJitEnabled(); 4202 } 4203 }); 4204 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>"); 4205 RuntimeInit.setApplicationObject(mAppThread.asBinder()); 4206 IActivityManager mgr = ActivityManagerNative.getDefault(); 4207 try { 4208 mgr.attachApplication(mAppThread); 4209 } catch (RemoteException ex) { 4210 // Ignore 4211 } 4212 } else { 4213 // Don't set application object here -- if the system crashes, 4214 // we can't display an alert, we just want to die die die. 4215 android.ddm.DdmHandleAppName.setAppName("system_process"); 4216 try { 4217 mInstrumentation = new Instrumentation(); 4218 ContextImpl context = new ContextImpl(); 4219 context.init(getSystemContext().mPackageInfo, null, this); 4220 Application app = Instrumentation.newApplication(Application.class, context); 4221 mAllApplications.add(app); 4222 mInitialApplication = app; 4223 app.onCreate(); 4224 } catch (Exception e) { 4225 throw new RuntimeException( 4226 "Unable to instantiate Application():" + e.toString(), e); 4227 } 4228 } 4229 4230 ViewRootImpl.addConfigCallback(new ComponentCallbacks2() { 4231 public void onConfigurationChanged(Configuration newConfig) { 4232 synchronized (mPackages) { 4233 // We need to apply this change to the resources 4234 // immediately, because upon returning the view 4235 // hierarchy will be informed about it. 4236 if (applyConfigurationToResourcesLocked(newConfig, null)) { 4237 // This actually changed the resources! Tell 4238 // everyone about it. 4239 if (mPendingConfiguration == null || 4240 mPendingConfiguration.isOtherSeqNewer(newConfig)) { 4241 mPendingConfiguration = newConfig; 4242 4243 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig); 4244 } 4245 } 4246 } 4247 } 4248 public void onLowMemory() { 4249 } 4250 public void onTrimMemory(int level) { 4251 } 4252 }); 4253 } 4254 4255 public static final ActivityThread systemMain() { 4256 HardwareRenderer.disable(); 4257 ActivityThread thread = new ActivityThread(); 4258 thread.attach(true); 4259 return thread; 4260 } 4261 4262 public final void installSystemProviders(List<ProviderInfo> providers) { 4263 if (providers != null) { 4264 installContentProviders(mInitialApplication, providers); 4265 } 4266 } 4267 4268 public int getIntCoreSetting(String key, int defaultValue) { 4269 synchronized (mPackages) { 4270 if (mCoreSettings != null) { 4271 return mCoreSettings.getInt(key, defaultValue); 4272 } else { 4273 return defaultValue; 4274 } 4275 } 4276 } 4277 4278 public static void main(String[] args) { 4279 SamplingProfilerIntegration.start(); 4280 4281 // CloseGuard defaults to true and can be quite spammy. We 4282 // disable it here, but selectively enable it later (via 4283 // StrictMode) on debug builds, but using DropBox, not logs. 4284 CloseGuard.setEnabled(false); 4285 4286 Process.setArgV0("<pre-initialized>"); 4287 4288 Looper.prepareMainLooper(); 4289 if (sMainThreadHandler == null) { 4290 sMainThreadHandler = new Handler(); 4291 } 4292 4293 ActivityThread thread = new ActivityThread(); 4294 thread.attach(false); 4295 4296 if (false) { 4297 Looper.myLooper().setMessageLogging(new 4298 LogPrinter(Log.DEBUG, "ActivityThread")); 4299 } 4300 4301 Looper.loop(); 4302 4303 throw new RuntimeException("Main thread loop unexpectedly exited"); 4304 } 4305} 4306