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