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