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