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