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