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