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