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