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