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