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