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