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