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