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