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