blob: 47efddb66628a15b0a1bc40e8d22f3e47979e81e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Christopher Tate45281862010-03-05 15:46:30 -080019import android.app.backup.BackupAgent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import 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;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070027import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.ActivityInfo;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.IPackageManager;
31import android.content.pm.InstrumentationInfo;
32import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070033import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.pm.ProviderInfo;
35import android.content.pm.ServiceInfo;
36import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070037import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080042import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.Bitmap;
44import android.graphics.Canvas;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070045import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Bundle;
47import android.os.Debug;
48import android.os.Handler;
49import android.os.IBinder;
50import android.os.Looper;
51import android.os.Message;
52import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070053import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Process;
55import android.os.RemoteException;
56import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070057import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.SystemClock;
59import android.util.AndroidRuntimeException;
60import android.util.Config;
61import android.util.DisplayMetrics;
62import android.util.EventLog;
63import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -070064import android.util.LogPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080065import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.view.Display;
Romain Guy52339202010-09-03 16:04:46 -070067import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.View;
69import android.view.ViewDebug;
70import android.view.ViewManager;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080071import android.view.ViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.view.Window;
73import android.view.WindowManager;
74import android.view.WindowManagerImpl;
75
76import com.android.internal.os.BinderInternal;
77import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070078import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
81
82import java.io.File;
83import java.io.FileDescriptor;
84import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070085import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import java.io.PrintWriter;
87import java.lang.ref.WeakReference;
88import java.util.ArrayList;
89import java.util.HashMap;
90import java.util.Iterator;
91import java.util.List;
92import java.util.Locale;
93import java.util.Map;
94import java.util.TimeZone;
95import java.util.regex.Pattern;
96
Bob Leee5408332009-09-04 18:31:17 -070097import dalvik.system.SamplingProfiler;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099final class SuperNotCalledException extends AndroidRuntimeException {
100 public SuperNotCalledException(String msg) {
101 super(msg);
102 }
103}
104
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700105final class RemoteServiceException extends AndroidRuntimeException {
106 public RemoteServiceException(String msg) {
107 super(msg);
108 }
109}
110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111/**
112 * This manages the execution of the main thread in an
113 * application process, scheduling and executing activities,
114 * broadcasts, and other operations on it as the activity
115 * manager requests.
116 *
117 * {@hide}
118 */
119public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700120 /** @hide */
121 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700122 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700124 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700125 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700126 /** @hide */
127 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700128 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700129 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700130 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
132 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
133 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
134 private static final int LOG_ON_PAUSE_CALLED = 30021;
135 private static final int LOG_ON_RESUME_CALLED = 30022;
136
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700137 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700138
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700139 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700141 final ApplicationThread mAppThread = new ApplicationThread();
142 final Looper mLooper = Looper.myLooper();
143 final H mH = new H();
144 final HashMap<IBinder, ActivityClientRecord> mActivities
145 = new HashMap<IBinder, ActivityClientRecord>();
146 // List of new activities (via ActivityRecord.nextIdle) that should
147 // be reported when next we idle.
148 ActivityClientRecord mNewActivities = null;
149 // Number of activities that are currently visible on-screen.
150 int mNumVisibleActivities = 0;
151 final HashMap<IBinder, Service> mServices
152 = new HashMap<IBinder, Service>();
153 AppBindData mBoundApplication;
154 Configuration mConfiguration;
155 Configuration mResConfiguration;
156 Application mInitialApplication;
157 final ArrayList<Application> mAllApplications
158 = new ArrayList<Application>();
159 // set of instantiated backup agents, keyed by package name
160 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700161 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700162 Instrumentation mInstrumentation;
163 String mInstrumentationAppDir = null;
164 String mInstrumentationAppPackage = null;
165 String mInstrumentedAppDir = null;
166 boolean mSystemThread = false;
167 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700169 // These can be accessed by multiple threads; mPackages is the lock.
170 // XXX For now we keep around information about all packages we have
171 // seen, not removing entries from this map.
172 final HashMap<String, WeakReference<LoadedApk>> mPackages
173 = new HashMap<String, WeakReference<LoadedApk>>();
174 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
175 = new HashMap<String, WeakReference<LoadedApk>>();
176 Display mDisplay = null;
177 DisplayMetrics mDisplayMetrics = null;
178 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
179 = new HashMap<ResourcesKey, WeakReference<Resources> >();
180 final ArrayList<ActivityClientRecord> mRelaunchingActivities
181 = new ArrayList<ActivityClientRecord>();
182 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700184 // The lock of mProviderMap protects the following variables.
185 final HashMap<String, ProviderClientRecord> mProviderMap
186 = new HashMap<String, ProviderClientRecord>();
187 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
188 = new HashMap<IBinder, ProviderRefCount>();
189 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
190 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700192 final GcIdler mGcIdler = new GcIdler();
193 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700195 static Handler sMainThreadHandler; // set once in main()
196
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700197 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700199 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 Intent intent;
201 Bundle state;
202 Activity activity;
203 Window window;
204 Activity parent;
205 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700206 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 boolean paused;
208 boolean stopped;
209 boolean hideForNow;
210 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700211 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700212 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
214 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700215 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
217 List<ResultInfo> pendingResults;
218 List<Intent> pendingIntents;
219
220 boolean startsNotResumed;
221 boolean isForward;
222
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700223 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 parent = null;
225 embeddedID = null;
226 paused = false;
227 stopped = false;
228 hideForNow = false;
229 nextIdle = null;
230 }
231
232 public String toString() {
233 ComponentName componentName = intent.getComponent();
234 return "ActivityRecord{"
235 + Integer.toHexString(System.identityHashCode(this))
236 + " token=" + token + " " + (componentName == null
237 ? "no component name" : componentName.toShortString())
238 + "}";
239 }
240 }
241
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700242 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 final String mName;
244 final IContentProvider mProvider;
245 final ContentProvider mLocalProvider;
246
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700247 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 ContentProvider localProvider) {
249 mName = name;
250 mProvider = provider;
251 mLocalProvider = localProvider;
252 }
253
254 public void binderDied() {
255 removeDeadProvider(mName, mProvider);
256 }
257 }
258
259 private static final class NewIntentData {
260 List<Intent> intents;
261 IBinder token;
262 public String toString() {
263 return "NewIntentData{intents=" + intents + " token=" + token + "}";
264 }
265 }
266
Dianne Hackborne829fef2010-10-26 17:44:01 -0700267 private static final class ReceiverData extends BroadcastReceiver.PendingResult {
268 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
269 boolean ordered, boolean sticky, IBinder token) {
270 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
271 this.intent = intent;
272 }
273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 Intent intent;
275 ActivityInfo info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 public String toString() {
277 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700278 info.packageName + " resultCode=" + getResultCode()
279 + " resultData=" + getResultData() + " resultExtras="
280 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 }
282 }
283
Christopher Tate181fafa2009-05-14 11:12:14 -0700284 private static final class CreateBackupAgentData {
285 ApplicationInfo appInfo;
286 int backupMode;
287 public String toString() {
288 return "CreateBackupAgentData{appInfo=" + appInfo
289 + " backupAgent=" + appInfo.backupAgentName
290 + " mode=" + backupMode + "}";
291 }
292 }
Bob Leee5408332009-09-04 18:31:17 -0700293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 private static final class CreateServiceData {
295 IBinder token;
296 ServiceInfo info;
297 Intent intent;
298 public String toString() {
299 return "CreateServiceData{token=" + token + " className="
300 + info.name + " packageName=" + info.packageName
301 + " intent=" + intent + "}";
302 }
303 }
304
305 private static final class BindServiceData {
306 IBinder token;
307 Intent intent;
308 boolean rebind;
309 public String toString() {
310 return "BindServiceData{token=" + token + " intent=" + intent + "}";
311 }
312 }
313
314 private static final class ServiceArgsData {
315 IBinder token;
316 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700317 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 Intent args;
319 public String toString() {
320 return "ServiceArgsData{token=" + token + " startId=" + startId
321 + " args=" + args + "}";
322 }
323 }
324
325 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700326 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 String processName;
328 ApplicationInfo appInfo;
329 List<ProviderInfo> providers;
330 ComponentName instrumentationName;
331 String profileFile;
332 Bundle instrumentationArgs;
333 IInstrumentationWatcher instrumentationWatcher;
334 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700335 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 Configuration config;
337 boolean handlingProfiling;
338 public String toString() {
339 return "AppBindData{appInfo=" + appInfo + "}";
340 }
341 }
342
Dianne Hackborn625ac272010-09-17 18:29:22 -0700343 private static final class DumpComponentInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 FileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700345 IBinder token;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 String[] args;
347 boolean dumped;
348 }
349
350 private static final class ResultData {
351 IBinder token;
352 List<ResultInfo> results;
353 public String toString() {
354 return "ResultData{token=" + token + " results" + results + "}";
355 }
356 }
357
358 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800359 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 String what;
361 String who;
362 }
363
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700364 private static final class ProfilerControlData {
365 String path;
366 ParcelFileDescriptor fd;
367 }
368
Andy McFadden824c5102010-07-09 16:26:57 -0700369 private static final class DumpHeapData {
370 String path;
371 ParcelFileDescriptor fd;
372 }
373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 private final class ApplicationThread extends ApplicationThreadNative {
375 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
376 private static final String ONE_COUNT_COLUMN = "%17s %8d";
377 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700378 private static final String TWO_COUNT_COLUMNS_DB = "%20s %8d %20s %8d";
379 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 // Formatting for checkin service - update version if row format changes
382 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 public final void schedulePauseActivity(IBinder token, boolean finished,
385 boolean userLeaving, int configChanges) {
386 queueOrSendMessage(
387 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
388 token,
389 (userLeaving ? 1 : 0),
390 configChanges);
391 }
392
393 public final void scheduleStopActivity(IBinder token, boolean showWindow,
394 int configChanges) {
395 queueOrSendMessage(
396 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
397 token, 0, configChanges);
398 }
399
400 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
401 queueOrSendMessage(
402 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
403 token);
404 }
405
406 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
407 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
408 }
409
410 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
411 ResultData res = new ResultData();
412 res.token = token;
413 res.results = results;
414 queueOrSendMessage(H.SEND_RESULT, res);
415 }
416
417 // we use token to identify this activity without having to send the
418 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700419 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
421 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700422 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423
424 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700425 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 r.intent = intent;
427 r.activityInfo = info;
428 r.state = state;
429
430 r.pendingResults = pendingResults;
431 r.pendingIntents = pendingNewIntents;
432
433 r.startsNotResumed = notResumed;
434 r.isForward = isForward;
435
436 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
437 }
438
439 public final void scheduleRelaunchActivity(IBinder token,
440 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800441 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700442 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443
444 r.token = token;
445 r.pendingResults = pendingResults;
446 r.pendingIntents = pendingNewIntents;
447 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800448 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800450 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 mRelaunchingActivities.add(r);
452 }
Bob Leee5408332009-09-04 18:31:17 -0700453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
455 }
456
457 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
458 NewIntentData data = new NewIntentData();
459 data.intents = intents;
460 data.token = token;
461
462 queueOrSendMessage(H.NEW_INTENT, data);
463 }
464
465 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
466 int configChanges) {
467 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
468 configChanges);
469 }
470
471 public final void scheduleReceiver(Intent intent, ActivityInfo info,
472 int resultCode, String data, Bundle extras, boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700473 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
474 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 r.info = info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 queueOrSendMessage(H.RECEIVER, r);
477 }
478
Christopher Tate181fafa2009-05-14 11:12:14 -0700479 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
480 CreateBackupAgentData d = new CreateBackupAgentData();
481 d.appInfo = app;
482 d.backupMode = backupMode;
483
484 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
485 }
486
487 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
488 CreateBackupAgentData d = new CreateBackupAgentData();
489 d.appInfo = app;
490
491 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
492 }
493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 public final void scheduleCreateService(IBinder token,
495 ServiceInfo info) {
496 CreateServiceData s = new CreateServiceData();
497 s.token = token;
498 s.info = info;
499
500 queueOrSendMessage(H.CREATE_SERVICE, s);
501 }
502
503 public final void scheduleBindService(IBinder token, Intent intent,
504 boolean rebind) {
505 BindServiceData s = new BindServiceData();
506 s.token = token;
507 s.intent = intent;
508 s.rebind = rebind;
509
510 queueOrSendMessage(H.BIND_SERVICE, s);
511 }
512
513 public final void scheduleUnbindService(IBinder token, Intent intent) {
514 BindServiceData s = new BindServiceData();
515 s.token = token;
516 s.intent = intent;
517
518 queueOrSendMessage(H.UNBIND_SERVICE, s);
519 }
520
521 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700522 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 ServiceArgsData s = new ServiceArgsData();
524 s.token = token;
525 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700526 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 s.args = args;
528
529 queueOrSendMessage(H.SERVICE_ARGS, s);
530 }
531
532 public final void scheduleStopService(IBinder token) {
533 queueOrSendMessage(H.STOP_SERVICE, token);
534 }
535
536 public final void bindApplication(String processName,
537 ApplicationInfo appInfo, List<ProviderInfo> providers,
538 ComponentName instrumentationName, String profileFile,
539 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700540 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542
543 if (services != null) {
544 // Setup the service cache in the ServiceManager
545 ServiceManager.initServiceCache(services);
546 }
547
548 AppBindData data = new AppBindData();
549 data.processName = processName;
550 data.appInfo = appInfo;
551 data.providers = providers;
552 data.instrumentationName = instrumentationName;
553 data.profileFile = profileFile;
554 data.instrumentationArgs = instrumentationArgs;
555 data.instrumentationWatcher = instrumentationWatcher;
556 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700557 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 data.config = config;
559 queueOrSendMessage(H.BIND_APPLICATION, data);
560 }
561
562 public final void scheduleExit() {
563 queueOrSendMessage(H.EXIT_APPLICATION, null);
564 }
565
Christopher Tate5e1ab332009-09-01 20:32:49 -0700566 public final void scheduleSuicide() {
567 queueOrSendMessage(H.SUICIDE, null);
568 }
569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 public void requestThumbnail(IBinder token) {
571 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
572 }
573
574 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800575 synchronized (mPackages) {
576 if (mPendingConfiguration == null ||
577 mPendingConfiguration.isOtherSeqNewer(config)) {
578 mPendingConfiguration = config;
579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 }
581 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
582 }
583
584 public void updateTimeZone() {
585 TimeZone.setDefault(null);
586 }
587
588 public void processInBackground() {
589 mH.removeMessages(H.GC_WHEN_IDLE);
590 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
591 }
592
593 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700594 DumpComponentInfo data = new DumpComponentInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 data.fd = fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700596 data.token = servicetoken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 data.args = args;
598 data.dumped = false;
599 queueOrSendMessage(H.DUMP_SERVICE, data);
600 synchronized (data) {
601 while (!data.dumped) {
602 try {
603 data.wait();
604 } catch (InterruptedException e) {
605 // no need to do anything here, we will keep waiting until
606 // dumped is set
607 }
608 }
609 }
610 }
611
612 // This function exists to make sure all receiver dispatching is
613 // correctly ordered, since these are one-way calls and the binder driver
614 // applies transaction ordering per object for such calls.
615 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700616 int resultCode, String dataStr, Bundle extras, boolean ordered,
617 boolean sticky) throws RemoteException {
618 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
Bob Leee5408332009-09-04 18:31:17 -0700620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 public void scheduleLowMemory() {
622 queueOrSendMessage(H.LOW_MEMORY, null);
623 }
624
625 public void scheduleActivityConfigurationChanged(IBinder token) {
626 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
627 }
628
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700629 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
630 ProfilerControlData pcd = new ProfilerControlData();
631 pcd.path = path;
632 pcd.fd = fd;
633 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800634 }
635
Andy McFadden824c5102010-07-09 16:26:57 -0700636 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
637 DumpHeapData dhd = new DumpHeapData();
638 dhd.path = path;
639 dhd.fd = fd;
640 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
641 }
642
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700643 public void setSchedulingGroup(int group) {
644 // Note: do this immediately, since going into the foreground
645 // should happen regardless of what pending work we have to do
646 // and the activity manager will wait for us to report back that
647 // we are done before sending us to the background.
648 try {
649 Process.setProcessGroup(Process.myPid(), group);
650 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800651 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700652 }
653 }
Bob Leee5408332009-09-04 18:31:17 -0700654
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700655 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
656 Debug.getMemoryInfo(outInfo);
657 }
Bob Leee5408332009-09-04 18:31:17 -0700658
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700659 public void dispatchPackageBroadcast(int cmd, String[] packages) {
660 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
661 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700662
663 public void scheduleCrash(String msg) {
664 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
665 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700666
667 public void dumpActivity(FileDescriptor fd, IBinder activitytoken, String[] args) {
668 DumpComponentInfo data = new DumpComponentInfo();
669 data.fd = fd;
670 data.token = activitytoken;
671 data.args = args;
672 data.dumped = false;
673 queueOrSendMessage(H.DUMP_ACTIVITY, data);
674 synchronized (data) {
675 while (!data.dumped) {
676 try {
677 data.wait();
678 } catch (InterruptedException e) {
679 // no need to do anything here, we will keep waiting until
680 // dumped is set
681 }
682 }
683 }
684 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 @Override
687 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
688 long nativeMax = Debug.getNativeHeapSize() / 1024;
689 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
690 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
691
692 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
693 Debug.getMemoryInfo(memInfo);
694
695 final int nativeShared = memInfo.nativeSharedDirty;
696 final int dalvikShared = memInfo.dalvikSharedDirty;
697 final int otherShared = memInfo.otherSharedDirty;
698
699 final int nativePrivate = memInfo.nativePrivateDirty;
700 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
701 final int otherPrivate = memInfo.otherPrivateDirty;
702
703 Runtime runtime = Runtime.getRuntime();
704
705 long dalvikMax = runtime.totalMemory() / 1024;
706 long dalvikFree = runtime.freeMemory() / 1024;
707 long dalvikAllocated = dalvikMax - dalvikFree;
708 long viewInstanceCount = ViewDebug.getViewInstanceCount();
709 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700710 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
711 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 int globalAssetCount = AssetManager.getGlobalAssetCount();
713 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
714 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
715 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
716 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700717 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800719 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 // Check to see if we were called by checkin server. If so, print terse format.
722 boolean doCheckinFormat = false;
723 if (args != null) {
724 for (String arg : args) {
725 if ("-c".equals(arg)) doCheckinFormat = true;
726 }
727 }
Bob Leee5408332009-09-04 18:31:17 -0700728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 // For checkin, we print one long comma-separated list of values
730 if (doCheckinFormat) {
731 // NOTE: if you change anything significant below, also consider changing
732 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700733 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 // Header
737 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
738 pw.print(Process.myPid()); pw.print(',');
739 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 // Heap info - max
742 pw.print(nativeMax); pw.print(',');
743 pw.print(dalvikMax); pw.print(',');
744 pw.print("N/A,");
745 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 // Heap info - allocated
748 pw.print(nativeAllocated); pw.print(',');
749 pw.print(dalvikAllocated); pw.print(',');
750 pw.print("N/A,");
751 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 // Heap info - free
754 pw.print(nativeFree); pw.print(',');
755 pw.print(dalvikFree); pw.print(',');
756 pw.print("N/A,");
757 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 // Heap info - proportional set size
760 pw.print(memInfo.nativePss); pw.print(',');
761 pw.print(memInfo.dalvikPss); pw.print(',');
762 pw.print(memInfo.otherPss); pw.print(',');
763 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700766 pw.print(nativeShared); pw.print(',');
767 pw.print(dalvikShared); pw.print(',');
768 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700772 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 pw.print(dalvikPrivate); pw.print(',');
774 pw.print(otherPrivate); pw.print(',');
775 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 // Object counts
778 pw.print(viewInstanceCount); pw.print(',');
779 pw.print(viewRootInstanceCount); pw.print(',');
780 pw.print(appContextInstanceCount); pw.print(',');
781 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 pw.print(globalAssetCount); pw.print(',');
784 pw.print(globalAssetManagerCount); pw.print(',');
785 pw.print(binderLocalObjectCount); pw.print(',');
786 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 pw.print(binderDeathObjectCount); pw.print(',');
789 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 // SQL
792 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800793 pw.print(stats.memoryUsed / 1024); pw.print(',');
794 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
795 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
796 for (int i = 0; i < stats.dbStats.size(); i++) {
797 DbStats dbStats = stats.dbStats.get(i);
798 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700799 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800800 pw.print(',');
801 }
Bob Leee5408332009-09-04 18:31:17 -0700802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 return;
804 }
Bob Leee5408332009-09-04 18:31:17 -0700805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 // otherwise, show human-readable format
807 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
808 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
809 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
810 nativeAllocated + dalvikAllocated);
811 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
812 nativeFree + dalvikFree);
813
814 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
815 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
816
817 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
818 nativeShared + dalvikShared + otherShared);
819 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
820 nativePrivate + dalvikPrivate + otherPrivate);
821
822 pw.println(" ");
823 pw.println(" Objects");
824 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
825 viewRootInstanceCount);
826
827 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
828 "Activities:", activityInstanceCount);
829
830 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
831 "AssetManagers:", globalAssetManagerCount);
832
833 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
834 "Proxy Binders:", binderProxyObjectCount);
835 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
836
837 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 // SQLite mem info
840 pw.println(" ");
841 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700842 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800843 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700844 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
845 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800846 pw.println(" ");
847 int N = stats.dbStats.size();
848 if (N > 0) {
849 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700850 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
851 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800852 for (int i = 0; i < N; i++) {
853 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700854 printRow(pw, DB_INFO_FORMAT,
855 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
856 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
857 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
858 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800859 }
860 }
Bob Leee5408332009-09-04 18:31:17 -0700861
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700862 // Asset details.
863 String assetAlloc = AssetManager.getAssetAllocations();
864 if (assetAlloc != null) {
865 pw.println(" ");
866 pw.println(" Asset Allocations");
867 pw.print(assetAlloc);
868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 }
870
871 private void printRow(PrintWriter pw, String format, Object...objs) {
872 pw.println(String.format(format, objs));
873 }
874 }
875
876 private final class H extends Handler {
877 public static final int LAUNCH_ACTIVITY = 100;
878 public static final int PAUSE_ACTIVITY = 101;
879 public static final int PAUSE_ACTIVITY_FINISHING= 102;
880 public static final int STOP_ACTIVITY_SHOW = 103;
881 public static final int STOP_ACTIVITY_HIDE = 104;
882 public static final int SHOW_WINDOW = 105;
883 public static final int HIDE_WINDOW = 106;
884 public static final int RESUME_ACTIVITY = 107;
885 public static final int SEND_RESULT = 108;
886 public static final int DESTROY_ACTIVITY = 109;
887 public static final int BIND_APPLICATION = 110;
888 public static final int EXIT_APPLICATION = 111;
889 public static final int NEW_INTENT = 112;
890 public static final int RECEIVER = 113;
891 public static final int CREATE_SERVICE = 114;
892 public static final int SERVICE_ARGS = 115;
893 public static final int STOP_SERVICE = 116;
894 public static final int REQUEST_THUMBNAIL = 117;
895 public static final int CONFIGURATION_CHANGED = 118;
896 public static final int CLEAN_UP_CONTEXT = 119;
897 public static final int GC_WHEN_IDLE = 120;
898 public static final int BIND_SERVICE = 121;
899 public static final int UNBIND_SERVICE = 122;
900 public static final int DUMP_SERVICE = 123;
901 public static final int LOW_MEMORY = 124;
902 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
903 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800904 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700905 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700906 public static final int DESTROY_BACKUP_AGENT = 129;
907 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700908 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800909 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700910 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700911 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700912 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700913 public static final int DUMP_ACTIVITY = 136;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700915 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 switch (code) {
917 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
918 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
919 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
920 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
921 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
922 case SHOW_WINDOW: return "SHOW_WINDOW";
923 case HIDE_WINDOW: return "HIDE_WINDOW";
924 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
925 case SEND_RESULT: return "SEND_RESULT";
926 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
927 case BIND_APPLICATION: return "BIND_APPLICATION";
928 case EXIT_APPLICATION: return "EXIT_APPLICATION";
929 case NEW_INTENT: return "NEW_INTENT";
930 case RECEIVER: return "RECEIVER";
931 case CREATE_SERVICE: return "CREATE_SERVICE";
932 case SERVICE_ARGS: return "SERVICE_ARGS";
933 case STOP_SERVICE: return "STOP_SERVICE";
934 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
935 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
936 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
937 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
938 case BIND_SERVICE: return "BIND_SERVICE";
939 case UNBIND_SERVICE: return "UNBIND_SERVICE";
940 case DUMP_SERVICE: return "DUMP_SERVICE";
941 case LOW_MEMORY: return "LOW_MEMORY";
942 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
943 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800944 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700945 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
946 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700947 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700948 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800949 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700950 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700951 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -0700952 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -0700953 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
955 }
956 return "(unknown)";
957 }
958 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700959 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 switch (msg.what) {
961 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700962 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963
964 r.packageInfo = getPackageInfoNoCheck(
965 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700966 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 } break;
968 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700969 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 handleRelaunchActivity(r, msg.arg1);
971 } break;
972 case PAUSE_ACTIVITY:
973 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700974 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 break;
976 case PAUSE_ACTIVITY_FINISHING:
977 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
978 break;
979 case STOP_ACTIVITY_SHOW:
980 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
981 break;
982 case STOP_ACTIVITY_HIDE:
983 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
984 break;
985 case SHOW_WINDOW:
986 handleWindowVisibility((IBinder)msg.obj, true);
987 break;
988 case HIDE_WINDOW:
989 handleWindowVisibility((IBinder)msg.obj, false);
990 break;
991 case RESUME_ACTIVITY:
992 handleResumeActivity((IBinder)msg.obj, true,
993 msg.arg1 != 0);
994 break;
995 case SEND_RESULT:
996 handleSendResult((ResultData)msg.obj);
997 break;
998 case DESTROY_ACTIVITY:
999 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1000 msg.arg2, false);
1001 break;
1002 case BIND_APPLICATION:
1003 AppBindData data = (AppBindData)msg.obj;
1004 handleBindApplication(data);
1005 break;
1006 case EXIT_APPLICATION:
1007 if (mInitialApplication != null) {
1008 mInitialApplication.onTerminate();
1009 }
1010 Looper.myLooper().quit();
1011 break;
1012 case NEW_INTENT:
1013 handleNewIntent((NewIntentData)msg.obj);
1014 break;
1015 case RECEIVER:
1016 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001017 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 break;
1019 case CREATE_SERVICE:
1020 handleCreateService((CreateServiceData)msg.obj);
1021 break;
1022 case BIND_SERVICE:
1023 handleBindService((BindServiceData)msg.obj);
1024 break;
1025 case UNBIND_SERVICE:
1026 handleUnbindService((BindServiceData)msg.obj);
1027 break;
1028 case SERVICE_ARGS:
1029 handleServiceArgs((ServiceArgsData)msg.obj);
1030 break;
1031 case STOP_SERVICE:
1032 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001033 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 break;
1035 case REQUEST_THUMBNAIL:
1036 handleRequestThumbnail((IBinder)msg.obj);
1037 break;
1038 case CONFIGURATION_CHANGED:
1039 handleConfigurationChanged((Configuration)msg.obj);
1040 break;
1041 case CLEAN_UP_CONTEXT:
1042 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1043 cci.context.performFinalCleanup(cci.who, cci.what);
1044 break;
1045 case GC_WHEN_IDLE:
1046 scheduleGcIdler();
1047 break;
1048 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001049 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 break;
1051 case LOW_MEMORY:
1052 handleLowMemory();
1053 break;
1054 case ACTIVITY_CONFIGURATION_CHANGED:
1055 handleActivityConfigurationChanged((IBinder)msg.obj);
1056 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001057 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001058 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001059 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001060 case CREATE_BACKUP_AGENT:
1061 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1062 break;
1063 case DESTROY_BACKUP_AGENT:
1064 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1065 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001066 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001067 Process.killProcess(Process.myPid());
1068 break;
1069 case REMOVE_PROVIDER:
1070 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001071 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001072 case ENABLE_JIT:
1073 ensureJitEnabled();
1074 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001075 case DISPATCH_PACKAGE_BROADCAST:
1076 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1077 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001078 case SCHEDULE_CRASH:
1079 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001080 case DUMP_HEAP:
1081 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1082 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001083 case DUMP_ACTIVITY:
1084 handleDumpActivity((DumpComponentInfo)msg.obj);
1085 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001087 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 }
Bob Leee5408332009-09-04 18:31:17 -07001089
1090 void maybeSnapshot() {
1091 if (mBoundApplication != null) {
Sen Hubde75702010-05-28 01:54:03 -07001092 // convert the *private* ActivityThread.PackageInfo to *public* known
1093 // android.content.pm.PackageInfo
1094 String packageName = mBoundApplication.info.mPackageName;
1095 android.content.pm.PackageInfo packageInfo = null;
1096 try {
1097 Context context = getSystemContext();
1098 if(context == null) {
1099 Log.e(TAG, "cannot get a valid context");
1100 return;
1101 }
1102 PackageManager pm = context.getPackageManager();
1103 if(pm == null) {
1104 Log.e(TAG, "cannot get a valid PackageManager");
1105 return;
1106 }
1107 packageInfo = pm.getPackageInfo(
1108 packageName, PackageManager.GET_ACTIVITIES);
1109 } catch (NameNotFoundException e) {
1110 Log.e(TAG, "cannot get package info for " + packageName, e);
1111 }
1112 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001113 }
1114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116
1117 private final class Idler implements MessageQueue.IdleHandler {
1118 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001119 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 if (a != null) {
1121 mNewActivities = null;
1122 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001123 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001125 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 TAG, "Reporting idle of " + a +
1127 " finished=" +
1128 (a.activity != null ? a.activity.mFinished : false));
1129 if (a.activity != null && !a.activity.mFinished) {
1130 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001131 am.activityIdle(a.token, a.createdConfig);
1132 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 } catch (RemoteException ex) {
1134 }
1135 }
1136 prev = a;
1137 a = a.nextIdle;
1138 prev.nextIdle = null;
1139 } while (a != null);
1140 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001141 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 return false;
1143 }
1144 }
1145
1146 final class GcIdler implements MessageQueue.IdleHandler {
1147 public final boolean queueIdle() {
1148 doGcIfNeeded();
1149 return false;
1150 }
1151 }
1152
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001153 private final static class ResourcesKey {
1154 final private String mResDir;
1155 final private float mScale;
1156 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001157
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001158 ResourcesKey(String resDir, float scale) {
1159 mResDir = resDir;
1160 mScale = scale;
1161 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1162 }
Bob Leee5408332009-09-04 18:31:17 -07001163
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001164 @Override
1165 public int hashCode() {
1166 return mHash;
1167 }
1168
1169 @Override
1170 public boolean equals(Object obj) {
1171 if (!(obj instanceof ResourcesKey)) {
1172 return false;
1173 }
1174 ResourcesKey peer = (ResourcesKey) obj;
1175 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1176 }
1177 }
1178
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001179 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001180 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001183 public static final String currentPackageName() {
1184 ActivityThread am = currentActivityThread();
1185 return (am != null && am.mBoundApplication != null)
1186 ? am.mBoundApplication.processName : null;
1187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001189 public static final Application currentApplication() {
1190 ActivityThread am = currentActivityThread();
1191 return am != null ? am.mInitialApplication : null;
1192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001194 public static IPackageManager getPackageManager() {
1195 if (sPackageManager != null) {
1196 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1197 return sPackageManager;
1198 }
1199 IBinder b = ServiceManager.getService("package");
1200 //Slog.v("PackageManager", "default service binder = " + b);
1201 sPackageManager = IPackageManager.Stub.asInterface(b);
1202 //Slog.v("PackageManager", "default service = " + sPackageManager);
1203 return sPackageManager;
1204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001206 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1207 if (mDisplayMetrics != null && !forceUpdate) {
1208 return mDisplayMetrics;
1209 }
1210 if (mDisplay == null) {
1211 WindowManager wm = WindowManagerImpl.getDefault();
1212 mDisplay = wm.getDefaultDisplay();
1213 }
1214 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1215 mDisplay.getMetrics(metrics);
1216 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1217 // + metrics.heightPixels + " den=" + metrics.density
1218 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1219 return metrics;
1220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001222 /**
1223 * Creates the top level Resources for applications with the given compatibility info.
1224 *
1225 * @param resDir the resource directory.
1226 * @param compInfo the compability info. It will use the default compatibility info when it's
1227 * null.
1228 */
1229 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1230 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1231 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001233 // Resources is app scale dependent.
1234 if (false) {
1235 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1236 + compInfo.applicationScale);
1237 }
1238 WeakReference<Resources> wr = mActiveResources.get(key);
1239 r = wr != null ? wr.get() : null;
1240 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1241 if (r != null && r.getAssets().isUpToDate()) {
1242 if (false) {
1243 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1244 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1245 }
1246 return r;
1247 }
1248 }
1249
1250 //if (r != null) {
1251 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1252 // + r + " " + resDir);
1253 //}
1254
1255 AssetManager assets = new AssetManager();
1256 if (assets.addAssetPath(resDir) == 0) {
1257 return null;
1258 }
1259
1260 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1261 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1262 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1263 if (false) {
1264 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1265 + r.getConfiguration() + " appScale="
1266 + r.getCompatibilityInfo().applicationScale);
1267 }
1268
1269 synchronized (mPackages) {
1270 WeakReference<Resources> wr = mActiveResources.get(key);
1271 Resources existing = wr != null ? wr.get() : null;
1272 if (existing != null && existing.getAssets().isUpToDate()) {
1273 // Someone else already created the resources while we were
1274 // unlocked; go ahead and use theirs.
1275 r.getAssets().close();
1276 return existing;
1277 }
1278
1279 // XXX need to remove entries when weak references go away
1280 mActiveResources.put(key, new WeakReference<Resources>(r));
1281 return r;
1282 }
1283 }
1284
1285 /**
1286 * Creates the top level resources for the given package.
1287 */
1288 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1289 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1290 }
1291
1292 final Handler getHandler() {
1293 return mH;
1294 }
1295
1296 public final LoadedApk getPackageInfo(String packageName, int flags) {
1297 synchronized (mPackages) {
1298 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1300 ref = mPackages.get(packageName);
1301 } else {
1302 ref = mResourcePackages.get(packageName);
1303 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001304 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001305 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001306 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1307 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 if (packageInfo != null && (packageInfo.mResources == null
1309 || packageInfo.mResources.getAssets().isUpToDate())) {
1310 if (packageInfo.isSecurityViolation()
1311 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1312 throw new SecurityException(
1313 "Requesting code from " + packageName
1314 + " to be run in process "
1315 + mBoundApplication.processName
1316 + "/" + mBoundApplication.appInfo.uid);
1317 }
1318 return packageInfo;
1319 }
1320 }
1321
1322 ApplicationInfo ai = null;
1323 try {
1324 ai = getPackageManager().getApplicationInfo(packageName,
1325 PackageManager.GET_SHARED_LIBRARY_FILES);
1326 } catch (RemoteException e) {
1327 }
1328
1329 if (ai != null) {
1330 return getPackageInfo(ai, flags);
1331 }
1332
1333 return null;
1334 }
1335
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001336 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1338 boolean securityViolation = includeCode && ai.uid != 0
1339 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1340 ? ai.uid != mBoundApplication.appInfo.uid : true);
1341 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1342 |Context.CONTEXT_IGNORE_SECURITY))
1343 == Context.CONTEXT_INCLUDE_CODE) {
1344 if (securityViolation) {
1345 String msg = "Requesting code from " + ai.packageName
1346 + " (with uid " + ai.uid + ")";
1347 if (mBoundApplication != null) {
1348 msg = msg + " to be run in process "
1349 + mBoundApplication.processName + " (with uid "
1350 + mBoundApplication.appInfo.uid + ")";
1351 }
1352 throw new SecurityException(msg);
1353 }
1354 }
1355 return getPackageInfo(ai, null, securityViolation, includeCode);
1356 }
1357
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001358 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 return getPackageInfo(ai, null, false, true);
1360 }
1361
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001362 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1364 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001365 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 if (includeCode) {
1367 ref = mPackages.get(aInfo.packageName);
1368 } else {
1369 ref = mResourcePackages.get(aInfo.packageName);
1370 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001371 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 if (packageInfo == null || (packageInfo.mResources != null
1373 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001374 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 : "Loading resource-only package ") + aInfo.packageName
1376 + " (in " + (mBoundApplication != null
1377 ? mBoundApplication.processName : null)
1378 + ")");
1379 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001380 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 securityViolation, includeCode &&
1382 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1383 if (includeCode) {
1384 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001385 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 } else {
1387 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001388 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
1390 }
1391 return packageInfo;
1392 }
1393 }
1394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 ActivityThread() {
1396 }
1397
1398 public ApplicationThread getApplicationThread()
1399 {
1400 return mAppThread;
1401 }
1402
1403 public Instrumentation getInstrumentation()
1404 {
1405 return mInstrumentation;
1406 }
1407
1408 public Configuration getConfiguration() {
1409 return mConfiguration;
1410 }
1411
1412 public boolean isProfiling() {
1413 return mBoundApplication != null && mBoundApplication.profileFile != null;
1414 }
1415
1416 public String getProfileFilePath() {
1417 return mBoundApplication.profileFile;
1418 }
1419
1420 public Looper getLooper() {
1421 return mLooper;
1422 }
1423
1424 public Application getApplication() {
1425 return mInitialApplication;
1426 }
Bob Leee5408332009-09-04 18:31:17 -07001427
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001428 public String getProcessName() {
1429 return mBoundApplication.processName;
1430 }
Bob Leee5408332009-09-04 18:31:17 -07001431
Dianne Hackborn21556372010-02-04 16:34:40 -08001432 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 synchronized (this) {
1434 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001435 ContextImpl context =
1436 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001437 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 context.init(info, null, this);
1439 context.getResources().updateConfiguration(
1440 getConfiguration(), getDisplayMetricsLocked(false));
1441 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001442 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 // + ": " + context.getResources().getConfiguration());
1444 }
1445 }
1446 return mSystemContext;
1447 }
1448
Mike Cleron432b7132009-09-24 15:28:29 -07001449 public void installSystemApplicationInfo(ApplicationInfo info) {
1450 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001451 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001452 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001453 }
1454 }
1455
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001456 void ensureJitEnabled() {
1457 if (!mJitEnabled) {
1458 mJitEnabled = true;
1459 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1460 }
1461 }
1462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 void scheduleGcIdler() {
1464 if (!mGcIdlerScheduled) {
1465 mGcIdlerScheduled = true;
1466 Looper.myQueue().addIdleHandler(mGcIdler);
1467 }
1468 mH.removeMessages(H.GC_WHEN_IDLE);
1469 }
1470
1471 void unscheduleGcIdler() {
1472 if (mGcIdlerScheduled) {
1473 mGcIdlerScheduled = false;
1474 Looper.myQueue().removeIdleHandler(mGcIdler);
1475 }
1476 mH.removeMessages(H.GC_WHEN_IDLE);
1477 }
1478
1479 void doGcIfNeeded() {
1480 mGcIdlerScheduled = false;
1481 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001482 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 // + "m now=" + now);
1484 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001485 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 BinderInternal.forceGc("bg");
1487 }
1488 }
1489
1490 public final ActivityInfo resolveActivityInfo(Intent intent) {
1491 ActivityInfo aInfo = intent.resolveActivityInfo(
1492 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1493 if (aInfo == null) {
1494 // Throw an exception.
1495 Instrumentation.checkStartActivityResult(
1496 IActivityManager.START_CLASS_NOT_FOUND, intent);
1497 }
1498 return aInfo;
1499 }
Bob Leee5408332009-09-04 18:31:17 -07001500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001503 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001504 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001506 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 r.intent = intent;
1508 r.state = state;
1509 r.parent = parent;
1510 r.embeddedID = id;
1511 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001512 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 if (localLOGV) {
1514 ComponentName compname = intent.getComponent();
1515 String name;
1516 if (compname != null) {
1517 name = compname.toShortString();
1518 } else {
1519 name = "(Intent " + intent + ").getComponent() returned null";
1520 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001521 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 + ", comp=" + name
1523 + ", token=" + token);
1524 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001525 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
1527
1528 public final Activity getActivity(IBinder token) {
1529 return mActivities.get(token).activity;
1530 }
1531
1532 public final void sendActivityResult(
1533 IBinder token, String id, int requestCode,
1534 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001535 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001536 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1538 list.add(new ResultInfo(id, requestCode, resultCode, data));
1539 mAppThread.scheduleSendResult(token, list);
1540 }
1541
1542 // if the thread hasn't started yet, we don't have the handler, so just
1543 // save the messages until we're ready.
1544 private final void queueOrSendMessage(int what, Object obj) {
1545 queueOrSendMessage(what, obj, 0, 0);
1546 }
1547
1548 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1549 queueOrSendMessage(what, obj, arg1, 0);
1550 }
1551
1552 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1553 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001554 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1556 + ": " + arg1 + " / " + obj);
1557 Message msg = Message.obtain();
1558 msg.what = what;
1559 msg.obj = obj;
1560 msg.arg1 = arg1;
1561 msg.arg2 = arg2;
1562 mH.sendMessage(msg);
1563 }
1564 }
1565
Dianne Hackborn21556372010-02-04 16:34:40 -08001566 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 String what) {
1568 ContextCleanupInfo cci = new ContextCleanupInfo();
1569 cci.context = context;
1570 cci.who = who;
1571 cci.what = what;
1572 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1573 }
1574
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001575 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1577
1578 ActivityInfo aInfo = r.activityInfo;
1579 if (r.packageInfo == null) {
1580 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1581 Context.CONTEXT_INCLUDE_CODE);
1582 }
Bob Leee5408332009-09-04 18:31:17 -07001583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 ComponentName component = r.intent.getComponent();
1585 if (component == null) {
1586 component = r.intent.resolveActivity(
1587 mInitialApplication.getPackageManager());
1588 r.intent.setComponent(component);
1589 }
1590
1591 if (r.activityInfo.targetActivity != null) {
1592 component = new ComponentName(r.activityInfo.packageName,
1593 r.activityInfo.targetActivity);
1594 }
1595
1596 Activity activity = null;
1597 try {
1598 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1599 activity = mInstrumentation.newActivity(
1600 cl, component.getClassName(), r.intent);
1601 r.intent.setExtrasClassLoader(cl);
1602 if (r.state != null) {
1603 r.state.setClassLoader(cl);
1604 }
1605 } catch (Exception e) {
1606 if (!mInstrumentation.onException(activity, e)) {
1607 throw new RuntimeException(
1608 "Unable to instantiate activity " + component
1609 + ": " + e.toString(), e);
1610 }
1611 }
1612
1613 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001614 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001615
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001616 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1617 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 TAG, r + ": app=" + app
1619 + ", appName=" + app.getPackageName()
1620 + ", pkg=" + r.packageInfo.getPackageName()
1621 + ", comp=" + r.intent.getComponent().toShortString()
1622 + ", dir=" + r.packageInfo.getAppDir());
1623
1624 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001625 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 appContext.init(r.packageInfo, r.token, this);
1627 appContext.setOuterContext(activity);
1628 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1629 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001630 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001631 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001632 activity.attach(appContext, this, getInstrumentation(), r.token,
1633 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001634 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001635
Christopher Tateb70f3df2009-04-07 16:07:59 -07001636 if (customIntent != null) {
1637 activity.mIntent = customIntent;
1638 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001639 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 activity.mStartedActivity = false;
1641 int theme = r.activityInfo.getThemeResource();
1642 if (theme != 0) {
1643 activity.setTheme(theme);
1644 }
1645
1646 activity.mCalled = false;
1647 mInstrumentation.callActivityOnCreate(activity, r.state);
1648 if (!activity.mCalled) {
1649 throw new SuperNotCalledException(
1650 "Activity " + r.intent.getComponent().toShortString() +
1651 " did not call through to super.onCreate()");
1652 }
1653 r.activity = activity;
1654 r.stopped = true;
1655 if (!r.activity.mFinished) {
1656 activity.performStart();
1657 r.stopped = false;
1658 }
1659 if (!r.activity.mFinished) {
1660 if (r.state != null) {
1661 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1662 }
1663 }
1664 if (!r.activity.mFinished) {
1665 activity.mCalled = false;
1666 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1667 if (!activity.mCalled) {
1668 throw new SuperNotCalledException(
1669 "Activity " + r.intent.getComponent().toShortString() +
1670 " did not call through to super.onPostCreate()");
1671 }
1672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 }
1674 r.paused = true;
1675
1676 mActivities.put(r.token, r);
1677
1678 } catch (SuperNotCalledException e) {
1679 throw e;
1680
1681 } catch (Exception e) {
1682 if (!mInstrumentation.onException(activity, e)) {
1683 throw new RuntimeException(
1684 "Unable to start activity " + component
1685 + ": " + e.toString(), e);
1686 }
1687 }
1688
1689 return activity;
1690 }
1691
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001692 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 // If we are getting ready to gc after going to the background, well
1694 // we are back active so skip it.
1695 unscheduleGcIdler();
1696
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001697 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001699 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700
1701 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001702 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001703 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 handleResumeActivity(r.token, false, r.isForward);
1705
1706 if (!r.activity.mFinished && r.startsNotResumed) {
1707 // The activity manager actually wants this one to start out
1708 // paused, because it needs to be visible but isn't in the
1709 // foreground. We accomplish this by going through the
1710 // normal startup (because activities expect to go through
1711 // onResume() the first time they run, before their window
1712 // is displayed), and then pausing it. However, in this case
1713 // we do -not- need to do the full pause cycle (of freezing
1714 // and such) because the activity manager assumes it can just
1715 // retain the current state it has.
1716 try {
1717 r.activity.mCalled = false;
1718 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001719 // We need to keep around the original state, in case
1720 // we need to be created again.
1721 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 if (!r.activity.mCalled) {
1723 throw new SuperNotCalledException(
1724 "Activity " + r.intent.getComponent().toShortString() +
1725 " did not call through to super.onPause()");
1726 }
1727
1728 } catch (SuperNotCalledException e) {
1729 throw e;
1730
1731 } catch (Exception e) {
1732 if (!mInstrumentation.onException(r.activity, e)) {
1733 throw new RuntimeException(
1734 "Unable to pause activity "
1735 + r.intent.getComponent().toShortString()
1736 + ": " + e.toString(), e);
1737 }
1738 }
1739 r.paused = true;
1740 }
1741 } else {
1742 // If there was an error, for any reason, tell the activity
1743 // manager to stop us.
1744 try {
1745 ActivityManagerNative.getDefault()
1746 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1747 } catch (RemoteException ex) {
1748 }
1749 }
1750 }
1751
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001752 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 List<Intent> intents) {
1754 final int N = intents.size();
1755 for (int i=0; i<N; i++) {
1756 Intent intent = intents.get(i);
1757 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001758 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1760 }
1761 }
1762
1763 public final void performNewIntents(IBinder token,
1764 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001765 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 if (r != null) {
1767 final boolean resumed = !r.paused;
1768 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001769 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 mInstrumentation.callActivityOnPause(r.activity);
1771 }
1772 deliverNewIntents(r, intents);
1773 if (resumed) {
1774 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001775 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 }
1777 }
1778 }
Bob Leee5408332009-09-04 18:31:17 -07001779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 private final void handleNewIntent(NewIntentData data) {
1781 performNewIntents(data.token, data.intents);
1782 }
1783
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001784 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
1785
1786 /**
1787 * Return the Intent that's currently being handled by a
1788 * BroadcastReceiver on this thread, or null if none.
1789 * @hide
1790 */
1791 public static Intent getIntentBeingBroadcast() {
1792 return sCurrentBroadcastIntent.get();
1793 }
1794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 private final void handleReceiver(ReceiverData data) {
1796 // If we are getting ready to gc after going to the background, well
1797 // we are back active so skip it.
1798 unscheduleGcIdler();
1799
1800 String component = data.intent.getComponent().getClassName();
1801
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001802 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 data.info.applicationInfo);
1804
1805 IActivityManager mgr = ActivityManagerNative.getDefault();
1806
1807 BroadcastReceiver receiver = null;
1808 try {
1809 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1810 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001811 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1813 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001814 if (DEBUG_BROADCAST) Slog.i(TAG,
1815 "Finishing failed broadcast to " + data.intent.getComponent());
1816 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 throw new RuntimeException(
1818 "Unable to instantiate receiver " + component
1819 + ": " + e.toString(), e);
1820 }
1821
1822 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001823 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001824
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001825 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 TAG, "Performing receive of " + data.intent
1827 + ": app=" + app
1828 + ", appName=" + app.getPackageName()
1829 + ", pkg=" + packageInfo.getPackageName()
1830 + ", comp=" + data.intent.getComponent().toShortString()
1831 + ", dir=" + packageInfo.getAppDir());
1832
Dianne Hackborn21556372010-02-04 16:34:40 -08001833 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001834 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001835 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 receiver.onReceive(context.getReceiverRestrictedContext(),
1837 data.intent);
1838 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001839 if (DEBUG_BROADCAST) Slog.i(TAG,
1840 "Finishing failed broadcast to " + data.intent.getComponent());
1841 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 if (!mInstrumentation.onException(receiver, e)) {
1843 throw new RuntimeException(
1844 "Unable to start receiver " + component
1845 + ": " + e.toString(), e);
1846 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001847 } finally {
1848 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 }
1850
Dianne Hackborne829fef2010-10-26 17:44:01 -07001851 if (receiver.getPendingResult() != null) {
1852 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
1854 }
1855
Christopher Tate181fafa2009-05-14 11:12:14 -07001856 // Instantiate a BackupAgent and tell it that it's alive
1857 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001858 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001859
1860 // no longer idle; we have backup work to do
1861 unscheduleGcIdler();
1862
1863 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001864 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001865 String packageName = packageInfo.mPackageName;
1866 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001867 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001868 + " already exists");
1869 return;
1870 }
Bob Leee5408332009-09-04 18:31:17 -07001871
Christopher Tate181fafa2009-05-14 11:12:14 -07001872 BackupAgent agent = null;
1873 String classname = data.appInfo.backupAgentName;
1874 if (classname == null) {
1875 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001876 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001877 + packageName);
1878 return;
1879 }
1880 classname = "android.app.FullBackupAgent";
1881 }
1882 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001883 IBinder binder = null;
1884 try {
1885 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1886 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1887
1888 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001889 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001890 + data.appInfo.backupAgentName);
1891
Dianne Hackborn21556372010-02-04 16:34:40 -08001892 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001893 context.init(packageInfo, null, this);
1894 context.setOuterContext(agent);
1895 agent.attach(context);
1896
1897 agent.onCreate();
1898 binder = agent.onBind();
1899 mBackupAgents.put(packageName, agent);
1900 } catch (Exception e) {
1901 // If this is during restore, fail silently; otherwise go
1902 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001903 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001904 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1905 throw e;
1906 }
1907 // falling through with 'binder' still null
1908 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001909
1910 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001911 try {
1912 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1913 } catch (RemoteException e) {
1914 // nothing to do.
1915 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001916 } catch (Exception e) {
1917 throw new RuntimeException("Unable to create BackupAgent "
1918 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1919 }
1920 }
1921
1922 // Tear down a BackupAgent
1923 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001924 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001925
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001926 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001927 String packageName = packageInfo.mPackageName;
1928 BackupAgent agent = mBackupAgents.get(packageName);
1929 if (agent != null) {
1930 try {
1931 agent.onDestroy();
1932 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001933 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001934 e.printStackTrace();
1935 }
1936 mBackupAgents.remove(packageName);
1937 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001938 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001939 }
1940 }
1941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 private final void handleCreateService(CreateServiceData data) {
1943 // If we are getting ready to gc after going to the background, well
1944 // we are back active so skip it.
1945 unscheduleGcIdler();
1946
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001947 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 data.info.applicationInfo);
1949 Service service = null;
1950 try {
1951 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1952 service = (Service) cl.loadClass(data.info.name).newInstance();
1953 } catch (Exception e) {
1954 if (!mInstrumentation.onException(service, e)) {
1955 throw new RuntimeException(
1956 "Unable to instantiate service " + data.info.name
1957 + ": " + e.toString(), e);
1958 }
1959 }
1960
1961 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001962 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963
Dianne Hackborn21556372010-02-04 16:34:40 -08001964 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 context.init(packageInfo, null, this);
1966
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001967 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 context.setOuterContext(service);
1969 service.attach(context, this, data.info.name, data.token, app,
1970 ActivityManagerNative.getDefault());
1971 service.onCreate();
1972 mServices.put(data.token, service);
1973 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001974 ActivityManagerNative.getDefault().serviceDoneExecuting(
1975 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 } catch (RemoteException e) {
1977 // nothing to do.
1978 }
1979 } catch (Exception e) {
1980 if (!mInstrumentation.onException(service, e)) {
1981 throw new RuntimeException(
1982 "Unable to create service " + data.info.name
1983 + ": " + e.toString(), e);
1984 }
1985 }
1986 }
1987
1988 private final void handleBindService(BindServiceData data) {
1989 Service s = mServices.get(data.token);
1990 if (s != null) {
1991 try {
1992 data.intent.setExtrasClassLoader(s.getClassLoader());
1993 try {
1994 if (!data.rebind) {
1995 IBinder binder = s.onBind(data.intent);
1996 ActivityManagerNative.getDefault().publishService(
1997 data.token, data.intent, binder);
1998 } else {
1999 s.onRebind(data.intent);
2000 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002001 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002003 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 } catch (RemoteException ex) {
2005 }
2006 } catch (Exception e) {
2007 if (!mInstrumentation.onException(s, e)) {
2008 throw new RuntimeException(
2009 "Unable to bind to service " + s
2010 + " with " + data.intent + ": " + e.toString(), e);
2011 }
2012 }
2013 }
2014 }
2015
2016 private final void handleUnbindService(BindServiceData data) {
2017 Service s = mServices.get(data.token);
2018 if (s != null) {
2019 try {
2020 data.intent.setExtrasClassLoader(s.getClassLoader());
2021 boolean doRebind = s.onUnbind(data.intent);
2022 try {
2023 if (doRebind) {
2024 ActivityManagerNative.getDefault().unbindFinished(
2025 data.token, data.intent, doRebind);
2026 } else {
2027 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002028 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 }
2030 } catch (RemoteException ex) {
2031 }
2032 } catch (Exception e) {
2033 if (!mInstrumentation.onException(s, e)) {
2034 throw new RuntimeException(
2035 "Unable to unbind to service " + s
2036 + " with " + data.intent + ": " + e.toString(), e);
2037 }
2038 }
2039 }
2040 }
2041
Dianne Hackborn625ac272010-09-17 18:29:22 -07002042 private void handleDumpService(DumpComponentInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002044 Service s = mServices.get(info.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 if (s != null) {
2046 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2047 s.dump(info.fd, pw, info.args);
2048 pw.close();
2049 }
2050 } finally {
2051 synchronized (info) {
2052 info.dumped = true;
2053 info.notifyAll();
2054 }
2055 }
2056 }
2057
Dianne Hackborn625ac272010-09-17 18:29:22 -07002058 private void handleDumpActivity(DumpComponentInfo info) {
2059 try {
2060 ActivityClientRecord r = mActivities.get(info.token);
2061 if (r != null && r.activity != null) {
2062 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2063 r.activity.dump(info.fd, pw, info.args);
2064 pw.close();
2065 }
2066 } finally {
2067 synchronized (info) {
2068 info.dumped = true;
2069 info.notifyAll();
2070 }
2071 }
2072 }
2073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 private final void handleServiceArgs(ServiceArgsData data) {
2075 Service s = mServices.get(data.token);
2076 if (s != null) {
2077 try {
2078 if (data.args != null) {
2079 data.args.setExtrasClassLoader(s.getClassLoader());
2080 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002081 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002082
2083 QueuedWork.waitToFinish();
2084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002086 ActivityManagerNative.getDefault().serviceDoneExecuting(
2087 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 } catch (RemoteException e) {
2089 // nothing to do.
2090 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002091 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 } catch (Exception e) {
2093 if (!mInstrumentation.onException(s, e)) {
2094 throw new RuntimeException(
2095 "Unable to start service " + s
2096 + " with " + data.args + ": " + e.toString(), e);
2097 }
2098 }
2099 }
2100 }
2101
2102 private final void handleStopService(IBinder token) {
2103 Service s = mServices.remove(token);
2104 if (s != null) {
2105 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002106 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 s.onDestroy();
2108 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002109 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002111 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002113
2114 QueuedWork.waitToFinish();
2115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002117 ActivityManagerNative.getDefault().serviceDoneExecuting(
2118 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 } catch (RemoteException e) {
2120 // nothing to do.
2121 }
2122 } catch (Exception e) {
2123 if (!mInstrumentation.onException(s, e)) {
2124 throw new RuntimeException(
2125 "Unable to stop service " + s
2126 + ": " + e.toString(), e);
2127 }
2128 }
2129 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002130 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
2132
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002133 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002135 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002136 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 + " finished=" + r.activity.mFinished);
2138 if (r != null && !r.activity.mFinished) {
2139 if (clearHide) {
2140 r.hideForNow = false;
2141 r.activity.mStartedActivity = false;
2142 }
2143 try {
2144 if (r.pendingIntents != null) {
2145 deliverNewIntents(r, r.pendingIntents);
2146 r.pendingIntents = null;
2147 }
2148 if (r.pendingResults != null) {
2149 deliverResults(r, r.pendingResults);
2150 r.pendingResults = null;
2151 }
2152 r.activity.performResume();
2153
Bob Leee5408332009-09-04 18:31:17 -07002154 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 r.paused = false;
2158 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 r.state = null;
2160 } catch (Exception e) {
2161 if (!mInstrumentation.onException(r.activity, e)) {
2162 throw new RuntimeException(
2163 "Unable to resume activity "
2164 + r.intent.getComponent().toShortString()
2165 + ": " + e.toString(), e);
2166 }
2167 }
2168 }
2169 return r;
2170 }
2171
2172 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2173 // If we are getting ready to gc after going to the background, well
2174 // we are back active so skip it.
2175 unscheduleGcIdler();
2176
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002177 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178
2179 if (r != null) {
2180 final Activity a = r.activity;
2181
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002182 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 TAG, "Resume " + r + " started activity: " +
2184 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2185 + ", finished: " + a.mFinished);
2186
2187 final int forwardBit = isForward ?
2188 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 // If the window hasn't yet been added to the window manager,
2191 // and this guy didn't finish itself or start another activity,
2192 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002193 boolean willBeVisible = !a.mStartedActivity;
2194 if (!willBeVisible) {
2195 try {
2196 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2197 a.getActivityToken());
2198 } catch (RemoteException e) {
2199 }
2200 }
2201 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 r.window = r.activity.getWindow();
2203 View decor = r.window.getDecorView();
2204 decor.setVisibility(View.INVISIBLE);
2205 ViewManager wm = a.getWindowManager();
2206 WindowManager.LayoutParams l = r.window.getAttributes();
2207 a.mDecor = decor;
2208 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2209 l.softInputMode |= forwardBit;
2210 if (a.mVisibleFromClient) {
2211 a.mWindowAdded = true;
2212 wm.addView(decor, l);
2213 }
2214
2215 // If the window has already been added, but during resume
2216 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002217 // window visible.
2218 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002219 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 TAG, "Launch " + r + " mStartedActivity set");
2221 r.hideForNow = true;
2222 }
2223
2224 // The window is now visible if it has been added, we are not
2225 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002226 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002227 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002229 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002230 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 performConfigurationChanged(r.activity, r.newConfig);
2232 r.newConfig = null;
2233 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002234 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 + isForward);
2236 WindowManager.LayoutParams l = r.window.getAttributes();
2237 if ((l.softInputMode
2238 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2239 != forwardBit) {
2240 l.softInputMode = (l.softInputMode
2241 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2242 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002243 if (r.activity.mVisibleFromClient) {
2244 ViewManager wm = a.getWindowManager();
2245 View decor = r.window.getDecorView();
2246 wm.updateViewLayout(decor, l);
2247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 }
2249 r.activity.mVisibleFromServer = true;
2250 mNumVisibleActivities++;
2251 if (r.activity.mVisibleFromClient) {
2252 r.activity.makeVisible();
2253 }
2254 }
2255
2256 r.nextIdle = mNewActivities;
2257 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002258 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 TAG, "Scheduling idle handler for " + r);
2260 Looper.myQueue().addIdleHandler(new Idler());
2261
2262 } else {
2263 // If an exception was thrown when trying to resume, then
2264 // just end this activity.
2265 try {
2266 ActivityManagerNative.getDefault()
2267 .finishActivity(token, Activity.RESULT_CANCELED, null);
2268 } catch (RemoteException ex) {
2269 }
2270 }
2271 }
2272
2273 private int mThumbnailWidth = -1;
2274 private int mThumbnailHeight = -1;
2275
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002276 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 Bitmap thumbnail = null;
2278 try {
2279 int w = mThumbnailWidth;
2280 int h;
2281 if (w < 0) {
2282 Resources res = r.activity.getResources();
2283 mThumbnailHeight = h =
2284 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2285
2286 mThumbnailWidth = w =
2287 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2288 } else {
2289 h = mThumbnailHeight;
2290 }
2291
Jim Miller0b2a6d02010-07-13 18:01:29 -07002292 // On platforms where we don't want thumbnails, set dims to (0,0)
2293 if ((w > 0) && (h > 0)) {
2294 View topView = r.activity.getWindow().getDecorView();
2295
2296 // Maximize bitmap by capturing in native aspect.
2297 if (topView.getWidth() >= topView.getHeight()) {
2298 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2299 } else {
2300 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2301 }
2302
2303 thumbnail.eraseColor(0);
2304 Canvas cv = new Canvas(thumbnail);
2305 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2306 thumbnail = null;
2307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 } catch (Exception e) {
2311 if (!mInstrumentation.onException(r.activity, e)) {
2312 throw new RuntimeException(
2313 "Unable to create thumbnail of "
2314 + r.intent.getComponent().toShortString()
2315 + ": " + e.toString(), e);
2316 }
2317 thumbnail = null;
2318 }
2319
2320 return thumbnail;
2321 }
2322
2323 private final void handlePauseActivity(IBinder token, boolean finished,
2324 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002325 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002327 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 if (userLeaving) {
2329 performUserLeavingActivity(r);
2330 }
Bob Leee5408332009-09-04 18:31:17 -07002331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 r.activity.mConfigChangeFlags |= configChanges;
2333 Bundle state = performPauseActivity(token, finished, true);
2334
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002335 // Make sure any pending writes are now committed.
2336 QueuedWork.waitToFinish();
2337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 // Tell the activity manager we have paused.
2339 try {
2340 ActivityManagerNative.getDefault().activityPaused(token, state);
2341 } catch (RemoteException ex) {
2342 }
2343 }
2344 }
2345
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002346 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 mInstrumentation.callActivityOnUserLeaving(r.activity);
2348 }
2349
2350 final Bundle performPauseActivity(IBinder token, boolean finished,
2351 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002352 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 return r != null ? performPauseActivity(r, finished, saveState) : null;
2354 }
2355
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002356 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 boolean saveState) {
2358 if (r.paused) {
2359 if (r.activity.mFinished) {
2360 // If we are finishing, we won't call onResume() in certain cases.
2361 // So here we likewise don't want to call onPause() if the activity
2362 // isn't resumed.
2363 return null;
2364 }
2365 RuntimeException e = new RuntimeException(
2366 "Performing pause of activity that is not resumed: "
2367 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002368 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 }
2370 Bundle state = null;
2371 if (finished) {
2372 r.activity.mFinished = true;
2373 }
2374 try {
2375 // Next have the activity save its current state and managed dialogs...
2376 if (!r.activity.mFinished && saveState) {
2377 state = new Bundle();
2378 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2379 r.state = state;
2380 }
2381 // Now we are idle.
2382 r.activity.mCalled = false;
2383 mInstrumentation.callActivityOnPause(r.activity);
2384 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2385 if (!r.activity.mCalled) {
2386 throw new SuperNotCalledException(
2387 "Activity " + r.intent.getComponent().toShortString() +
2388 " did not call through to super.onPause()");
2389 }
2390
2391 } catch (SuperNotCalledException e) {
2392 throw e;
2393
2394 } catch (Exception e) {
2395 if (!mInstrumentation.onException(r.activity, e)) {
2396 throw new RuntimeException(
2397 "Unable to pause activity "
2398 + r.intent.getComponent().toShortString()
2399 + ": " + e.toString(), e);
2400 }
2401 }
2402 r.paused = true;
2403 return state;
2404 }
2405
2406 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002407 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 performStopActivityInner(r, null, false);
2409 }
2410
2411 private static class StopInfo {
2412 Bitmap thumbnail;
2413 CharSequence description;
2414 }
2415
2416 private final class ProviderRefCount {
2417 public int count;
2418 ProviderRefCount(int pCount) {
2419 count = pCount;
2420 }
2421 }
2422
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002423 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002425 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 if (r != null) {
2427 if (!keepShown && r.stopped) {
2428 if (r.activity.mFinished) {
2429 // If we are finishing, we won't call onResume() in certain
2430 // cases. So here we likewise don't want to call onStop()
2431 // if the activity isn't resumed.
2432 return;
2433 }
2434 RuntimeException e = new RuntimeException(
2435 "Performing stop of activity that is not resumed: "
2436 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002437 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 }
2439
2440 if (info != null) {
2441 try {
2442 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002443 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 info.description = r.activity.onCreateDescription();
2445 } catch (Exception e) {
2446 if (!mInstrumentation.onException(r.activity, e)) {
2447 throw new RuntimeException(
2448 "Unable to save state of activity "
2449 + r.intent.getComponent().toShortString()
2450 + ": " + e.toString(), e);
2451 }
2452 }
2453 }
2454
2455 if (!keepShown) {
2456 try {
2457 // Now we are idle.
2458 r.activity.performStop();
2459 } catch (Exception e) {
2460 if (!mInstrumentation.onException(r.activity, e)) {
2461 throw new RuntimeException(
2462 "Unable to stop activity "
2463 + r.intent.getComponent().toShortString()
2464 + ": " + e.toString(), e);
2465 }
2466 }
2467 r.stopped = true;
2468 }
2469
2470 r.paused = true;
2471 }
2472 }
2473
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002474 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 View v = r.activity.mDecor;
2476 if (v != null) {
2477 if (show) {
2478 if (!r.activity.mVisibleFromServer) {
2479 r.activity.mVisibleFromServer = true;
2480 mNumVisibleActivities++;
2481 if (r.activity.mVisibleFromClient) {
2482 r.activity.makeVisible();
2483 }
2484 }
2485 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002486 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002487 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 performConfigurationChanged(r.activity, r.newConfig);
2489 r.newConfig = null;
2490 }
2491 } else {
2492 if (r.activity.mVisibleFromServer) {
2493 r.activity.mVisibleFromServer = false;
2494 mNumVisibleActivities--;
2495 v.setVisibility(View.INVISIBLE);
2496 }
2497 }
2498 }
2499 }
2500
2501 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002502 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 r.activity.mConfigChangeFlags |= configChanges;
2504
2505 StopInfo info = new StopInfo();
2506 performStopActivityInner(r, info, show);
2507
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002508 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 TAG, "Finishing stop of " + r + ": show=" + show
2510 + " win=" + r.window);
2511
2512 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 // Tell activity manager we have been stopped.
2515 try {
2516 ActivityManagerNative.getDefault().activityStopped(
2517 r.token, info.thumbnail, info.description);
2518 } catch (RemoteException ex) {
2519 }
2520 }
2521
2522 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002523 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 if (r.stopped) {
2525 r.activity.performRestart();
2526 r.stopped = false;
2527 }
2528 }
2529
2530 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002531 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 if (!show && !r.stopped) {
2533 performStopActivityInner(r, null, show);
2534 } else if (show && r.stopped) {
2535 // If we are getting ready to gc after going to the background, well
2536 // we are back active so skip it.
2537 unscheduleGcIdler();
2538
2539 r.activity.performRestart();
2540 r.stopped = false;
2541 }
2542 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002543 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 TAG, "Handle window " + r + " visibility: " + show);
2545 updateVisibility(r, show);
2546 }
2547 }
2548
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002549 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 final int N = results.size();
2551 for (int i=0; i<N; i++) {
2552 ResultInfo ri = results.get(i);
2553 try {
2554 if (ri.mData != null) {
2555 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2556 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002557 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002558 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 r.activity.dispatchActivityResult(ri.mResultWho,
2560 ri.mRequestCode, ri.mResultCode, ri.mData);
2561 } catch (Exception e) {
2562 if (!mInstrumentation.onException(r.activity, e)) {
2563 throw new RuntimeException(
2564 "Failure delivering result " + ri + " to activity "
2565 + r.intent.getComponent().toShortString()
2566 + ": " + e.toString(), e);
2567 }
2568 }
2569 }
2570 }
2571
2572 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002573 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002574 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 if (r != null) {
2576 final boolean resumed = !r.paused;
2577 if (!r.activity.mFinished && r.activity.mDecor != null
2578 && r.hideForNow && resumed) {
2579 // We had hidden the activity because it started another
2580 // one... we have gotten a result back and we are not
2581 // paused, so make sure our window is visible.
2582 updateVisibility(r, true);
2583 }
2584 if (resumed) {
2585 try {
2586 // Now we are idle.
2587 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002588 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 mInstrumentation.callActivityOnPause(r.activity);
2590 if (!r.activity.mCalled) {
2591 throw new SuperNotCalledException(
2592 "Activity " + r.intent.getComponent().toShortString()
2593 + " did not call through to super.onPause()");
2594 }
2595 } catch (SuperNotCalledException e) {
2596 throw e;
2597 } catch (Exception e) {
2598 if (!mInstrumentation.onException(r.activity, e)) {
2599 throw new RuntimeException(
2600 "Unable to pause activity "
2601 + r.intent.getComponent().toShortString()
2602 + ": " + e.toString(), e);
2603 }
2604 }
2605 }
2606 deliverResults(r, res.results);
2607 if (resumed) {
2608 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002609 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 }
2611 }
2612 }
2613
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002614 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 return performDestroyActivity(token, finishing, 0, false);
2616 }
2617
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002618 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002620 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002621 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 if (r != null) {
2623 r.activity.mConfigChangeFlags |= configChanges;
2624 if (finishing) {
2625 r.activity.mFinished = true;
2626 }
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05002627 if (getNonConfigInstance) {
2628 r.activity.mChangingConfigurations = true;
2629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 if (!r.paused) {
2631 try {
2632 r.activity.mCalled = false;
2633 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002634 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 r.activity.getComponentName().getClassName());
2636 if (!r.activity.mCalled) {
2637 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002638 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 + " did not call through to super.onPause()");
2640 }
2641 } catch (SuperNotCalledException e) {
2642 throw e;
2643 } catch (Exception e) {
2644 if (!mInstrumentation.onException(r.activity, e)) {
2645 throw new RuntimeException(
2646 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002647 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 + ": " + e.toString(), e);
2649 }
2650 }
2651 r.paused = true;
2652 }
2653 if (!r.stopped) {
2654 try {
2655 r.activity.performStop();
2656 } catch (SuperNotCalledException e) {
2657 throw e;
2658 } catch (Exception e) {
2659 if (!mInstrumentation.onException(r.activity, e)) {
2660 throw new RuntimeException(
2661 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002662 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 + ": " + e.toString(), e);
2664 }
2665 }
2666 r.stopped = true;
2667 }
2668 if (getNonConfigInstance) {
2669 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002670 r.lastNonConfigurationInstances
2671 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 } catch (Exception e) {
2673 if (!mInstrumentation.onException(r.activity, e)) {
2674 throw new RuntimeException(
2675 "Unable to retain activity "
2676 + r.intent.getComponent().toShortString()
2677 + ": " + e.toString(), e);
2678 }
2679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 }
2681 try {
2682 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002683 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 if (!r.activity.mCalled) {
2685 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002686 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 " did not call through to super.onDestroy()");
2688 }
2689 if (r.window != null) {
2690 r.window.closeAllPanels();
2691 }
2692 } catch (SuperNotCalledException e) {
2693 throw e;
2694 } catch (Exception e) {
2695 if (!mInstrumentation.onException(r.activity, e)) {
2696 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002697 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2698 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 }
2700 }
2701 }
2702 mActivities.remove(token);
2703
2704 return r;
2705 }
2706
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002707 private static String safeToComponentShortString(Intent intent) {
2708 ComponentName component = intent.getComponent();
2709 return component == null ? "[Unknown]" : component.toShortString();
2710 }
2711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 private final void handleDestroyActivity(IBinder token, boolean finishing,
2713 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002714 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 configChanges, getNonConfigInstance);
2716 if (r != null) {
2717 WindowManager wm = r.activity.getWindowManager();
2718 View v = r.activity.mDecor;
2719 if (v != null) {
2720 if (r.activity.mVisibleFromServer) {
2721 mNumVisibleActivities--;
2722 }
2723 IBinder wtoken = v.getWindowToken();
2724 if (r.activity.mWindowAdded) {
2725 wm.removeViewImmediate(v);
2726 }
2727 if (wtoken != null) {
2728 WindowManagerImpl.getDefault().closeAll(wtoken,
2729 r.activity.getClass().getName(), "Activity");
2730 }
2731 r.activity.mDecor = null;
2732 }
2733 WindowManagerImpl.getDefault().closeAll(token,
2734 r.activity.getClass().getName(), "Activity");
2735
2736 // Mocked out contexts won't be participating in the normal
2737 // process lifecycle, but if we're running with a proper
2738 // ApplicationContext we need to have it tear down things
2739 // cleanly.
2740 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002741 if (c instanceof ContextImpl) {
2742 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 r.activity.getClass().getName(), "Activity");
2744 }
2745 }
2746 if (finishing) {
2747 try {
2748 ActivityManagerNative.getDefault().activityDestroyed(token);
2749 } catch (RemoteException ex) {
2750 // If the system process has died, it's game over for everyone.
2751 }
2752 }
2753 }
2754
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002755 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 // If we are getting ready to gc after going to the background, well
2757 // we are back active so skip it.
2758 unscheduleGcIdler();
2759
2760 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002761
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002762 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002763 + tmp.token + " with configChanges=0x"
2764 + Integer.toHexString(configChanges));
2765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 // First: make sure we have the most recent configuration and most
2767 // recent version of the activity, or skip it if some previous call
2768 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002769 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 int N = mRelaunchingActivities.size();
2771 IBinder token = tmp.token;
2772 tmp = null;
2773 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002774 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 if (r.token == token) {
2776 tmp = r;
2777 mRelaunchingActivities.remove(i);
2778 i--;
2779 N--;
2780 }
2781 }
Bob Leee5408332009-09-04 18:31:17 -07002782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002784 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 return;
2786 }
Bob Leee5408332009-09-04 18:31:17 -07002787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 if (mPendingConfiguration != null) {
2789 changedConfig = mPendingConfiguration;
2790 mPendingConfiguration = null;
2791 }
2792 }
Bob Leee5408332009-09-04 18:31:17 -07002793
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002794 if (tmp.createdConfig != null) {
2795 // If the activity manager is passing us its current config,
2796 // assume that is really what we want regardless of what we
2797 // may have pending.
2798 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002799 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2800 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2801 if (changedConfig == null
2802 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2803 changedConfig = tmp.createdConfig;
2804 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002805 }
2806 }
2807
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002808 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002809 + tmp.token + ": changedConfig=" + changedConfig);
2810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 // If there was a pending configuration change, execute it first.
2812 if (changedConfig != null) {
2813 handleConfigurationChanged(changedConfig);
2814 }
Bob Leee5408332009-09-04 18:31:17 -07002815
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002816 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002817 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 if (r == null) {
2819 return;
2820 }
Bob Leee5408332009-09-04 18:31:17 -07002821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002823 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 Bundle savedState = null;
2826 if (!r.paused) {
2827 savedState = performPauseActivity(r.token, false, true);
2828 }
Bob Leee5408332009-09-04 18:31:17 -07002829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 r.activity = null;
2833 r.window = null;
2834 r.hideForNow = false;
2835 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002836 // Merge any pending results and pending intents; don't just replace them
2837 if (tmp.pendingResults != null) {
2838 if (r.pendingResults == null) {
2839 r.pendingResults = tmp.pendingResults;
2840 } else {
2841 r.pendingResults.addAll(tmp.pendingResults);
2842 }
2843 }
2844 if (tmp.pendingIntents != null) {
2845 if (r.pendingIntents == null) {
2846 r.pendingIntents = tmp.pendingIntents;
2847 } else {
2848 r.pendingIntents.addAll(tmp.pendingIntents);
2849 }
2850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 r.startsNotResumed = tmp.startsNotResumed;
2852 if (savedState != null) {
2853 r.state = savedState;
2854 }
Bob Leee5408332009-09-04 18:31:17 -07002855
Christopher Tateb70f3df2009-04-07 16:07:59 -07002856 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 }
2858
2859 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002860 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 Bitmap thumbnail = createThumbnailBitmap(r);
2862 CharSequence description = null;
2863 try {
2864 description = r.activity.onCreateDescription();
2865 } catch (Exception e) {
2866 if (!mInstrumentation.onException(r.activity, e)) {
2867 throw new RuntimeException(
2868 "Unable to create description of activity "
2869 + r.intent.getComponent().toShortString()
2870 + ": " + e.toString(), e);
2871 }
2872 }
2873 //System.out.println("Reporting top thumbnail " + thumbnail);
2874 try {
2875 ActivityManagerNative.getDefault().reportThumbnail(
2876 token, thumbnail, description);
2877 } catch (RemoteException ex) {
2878 }
2879 }
2880
2881 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2882 boolean allActivities, Configuration newConfig) {
2883 ArrayList<ComponentCallbacks> callbacks
2884 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002887 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002889 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 Activity a = ar.activity;
2891 if (a != null) {
2892 if (!ar.activity.mFinished && (allActivities ||
2893 (a != null && !ar.paused))) {
2894 // If the activity is currently resumed, its configuration
2895 // needs to change right now.
2896 callbacks.add(a);
2897 } else if (newConfig != null) {
2898 // Otherwise, we will tell it about the change
2899 // the next time it is resumed or shown. Note that
2900 // the activity manager may, before then, decide the
2901 // activity needs to be destroyed to handle its new
2902 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002903 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002904 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 ar.newConfig = newConfig;
2906 }
2907 }
2908 }
2909 }
2910 if (mServices.size() > 0) {
2911 Iterator<Service> it = mServices.values().iterator();
2912 while (it.hasNext()) {
2913 callbacks.add(it.next());
2914 }
2915 }
2916 synchronized (mProviderMap) {
2917 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002918 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 while (it.hasNext()) {
2920 callbacks.add(it.next().mLocalProvider);
2921 }
2922 }
2923 }
2924 final int N = mAllApplications.size();
2925 for (int i=0; i<N; i++) {
2926 callbacks.add(mAllApplications.get(i));
2927 }
Bob Leee5408332009-09-04 18:31:17 -07002928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 return callbacks;
2930 }
Bob Leee5408332009-09-04 18:31:17 -07002931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 private final void performConfigurationChanged(
2933 ComponentCallbacks cb, Configuration config) {
2934 // Only for Activity objects, check that they actually call up to their
2935 // superclass implementation. ComponentCallbacks is an interface, so
2936 // we check the runtime type and act accordingly.
2937 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2938 if (activity != null) {
2939 activity.mCalled = false;
2940 }
Bob Leee5408332009-09-04 18:31:17 -07002941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 boolean shouldChangeConfig = false;
2943 if ((activity == null) || (activity.mCurrentConfig == null)) {
2944 shouldChangeConfig = true;
2945 } else {
Bob Leee5408332009-09-04 18:31:17 -07002946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 // If the new config is the same as the config this Activity
2948 // is already running with then don't bother calling
2949 // onConfigurationChanged
2950 int diff = activity.mCurrentConfig.diff(config);
2951 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 // If this activity doesn't handle any of the config changes
2954 // then don't bother calling onConfigurationChanged as we're
2955 // going to destroy it.
2956 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2957 shouldChangeConfig = true;
2958 }
2959 }
2960 }
Bob Leee5408332009-09-04 18:31:17 -07002961
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002962 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002963 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 if (shouldChangeConfig) {
2965 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 if (activity != null) {
2968 if (!activity.mCalled) {
2969 throw new SuperNotCalledException(
2970 "Activity " + activity.getLocalClassName() +
2971 " did not call through to super.onConfigurationChanged()");
2972 }
2973 activity.mConfigChangeFlags = 0;
2974 activity.mCurrentConfig = new Configuration(config);
2975 }
2976 }
2977 }
2978
Dianne Hackbornae078162010-03-18 11:29:37 -07002979 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002980 if (mResConfiguration == null) {
2981 mResConfiguration = new Configuration();
2982 }
2983 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002984 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002985 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002986 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002987 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002988 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002989 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002990
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002991 // set it for java, this also affects newly created Resources
2992 if (config.locale != null) {
2993 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 }
Bob Leee5408332009-09-04 18:31:17 -07002995
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002996 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07002997
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002998 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002999 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003000
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003001 Iterator<WeakReference<Resources>> it =
3002 mActiveResources.values().iterator();
3003 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3004 // mActiveResources.entrySet().iterator();
3005 while (it.hasNext()) {
3006 WeakReference<Resources> v = it.next();
3007 Resources r = v.get();
3008 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003009 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003010 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003011 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003012 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003013 // + " " + r + ": " + r.getConfiguration());
3014 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003015 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003016 it.remove();
3017 }
3018 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003019
3020 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003021 }
3022
3023 final void handleConfigurationChanged(Configuration config) {
3024
3025 ArrayList<ComponentCallbacks> callbacks = null;
3026
3027 synchronized (mPackages) {
3028 if (mPendingConfiguration != null) {
3029 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3030 config = mPendingConfiguration;
3031 }
3032 mPendingConfiguration = null;
3033 }
3034
3035 if (config == null) {
3036 return;
3037 }
3038
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003039 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003040 + config);
3041
3042 applyConfigurationToResourcesLocked(config);
3043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 if (mConfiguration == null) {
3045 mConfiguration = new Configuration();
3046 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003047 if (!mConfiguration.isOtherSeqNewer(config)) {
3048 return;
3049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 callbacks = collectComponentCallbacksLocked(false, config);
3053 }
Bob Leee5408332009-09-04 18:31:17 -07003054
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003055 if (callbacks != null) {
3056 final int N = callbacks.size();
3057 for (int i=0; i<N; i++) {
3058 performConfigurationChanged(callbacks.get(i), config);
3059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 }
3061 }
3062
3063 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003064 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 if (r == null || r.activity == null) {
3066 return;
3067 }
Bob Leee5408332009-09-04 18:31:17 -07003068
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003069 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003070 + r.activityInfo.name);
3071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 performConfigurationChanged(r.activity, mConfiguration);
3073 }
3074
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003075 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003076 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003077 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003078 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3079 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003080 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003081 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003082 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003083 } finally {
3084 try {
3085 pcd.fd.close();
3086 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003087 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003088 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003089 }
3090 } else {
3091 Debug.stopMethodTracing();
3092 }
3093 }
Bob Leee5408332009-09-04 18:31:17 -07003094
Andy McFadden824c5102010-07-09 16:26:57 -07003095 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3096 if (managed) {
3097 try {
3098 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3099 } catch (IOException e) {
3100 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3101 + " -- can the process access this path?");
3102 } finally {
3103 try {
3104 dhd.fd.close();
3105 } catch (IOException e) {
3106 Slog.w(TAG, "Failure closing profile fd", e);
3107 }
3108 }
3109 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003110 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003111 }
3112 }
3113
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003114 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3115 boolean hasPkgInfo = false;
3116 if (packages != null) {
3117 for (int i=packages.length-1; i>=0; i--) {
3118 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3119 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003120 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003121 ref = mPackages.get(packages[i]);
3122 if (ref != null && ref.get() != null) {
3123 hasPkgInfo = true;
3124 } else {
3125 ref = mResourcePackages.get(packages[i]);
3126 if (ref != null && ref.get() != null) {
3127 hasPkgInfo = true;
3128 }
3129 }
3130 }
3131 mPackages.remove(packages[i]);
3132 mResourcePackages.remove(packages[i]);
3133 }
3134 }
3135 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3136 hasPkgInfo);
3137 }
3138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 final void handleLowMemory() {
3140 ArrayList<ComponentCallbacks> callbacks
3141 = new ArrayList<ComponentCallbacks>();
3142
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003143 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 callbacks = collectComponentCallbacksLocked(true, null);
3145 }
Bob Leee5408332009-09-04 18:31:17 -07003146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 final int N = callbacks.size();
3148 for (int i=0; i<N; i++) {
3149 callbacks.get(i).onLowMemory();
3150 }
3151
Chris Tatece229052009-03-25 16:44:52 -07003152 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3153 if (Process.myUid() != Process.SYSTEM_UID) {
3154 int sqliteReleased = SQLiteDatabase.releaseMemory();
3155 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3156 }
Bob Leee5408332009-09-04 18:31:17 -07003157
Mike Reedcaf0df12009-04-27 14:32:05 -04003158 // Ask graphics to free up as much as possible (font/image caches)
3159 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160
3161 BinderInternal.forceGc("mem");
3162 }
3163
3164 private final void handleBindApplication(AppBindData data) {
3165 mBoundApplication = data;
3166 mConfiguration = new Configuration(data.config);
3167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003169 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 android.ddm.DdmHandleAppName.setAppName(data.processName);
3171
3172 /*
3173 * Before spawning a new process, reset the time zone to be the system time zone.
3174 * This needs to be done because the system time zone could have changed after the
3175 * the spawning of this process. Without doing this this process would have the incorrect
3176 * system time zone.
3177 */
3178 TimeZone.setDefault(null);
3179
3180 /*
3181 * Initialize the default locale in this process for the reasons we set the time zone.
3182 */
3183 Locale.setDefault(data.config.locale);
3184
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003185 /*
3186 * Update the system configuration since its preloaded and might not
3187 * reflect configuration changes. The configuration object passed
3188 * in AppBindData can be safely assumed to be up to date
3189 */
3190 Resources.getSystem().updateConfiguration(mConfiguration, null);
3191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 data.info = getPackageInfoNoCheck(data.appInfo);
3193
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003194 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003195 * For system applications on userdebug/eng builds, log stack
3196 * traces of disk and network access to dropbox for analysis.
3197 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003198 if ((data.appInfo.flags &
3199 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003200 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3201 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003202 }
3203
3204 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003205 * For apps targetting SDK Honeycomb or later, we don't allow
3206 * network usage on the main event loop / UI thread.
3207 *
3208 * Note to those grepping: this is what ultimately throws
3209 * NetworkOnMainThreadException ...
3210 */
3211 if (data.appInfo.targetSdkVersion > 9) {
3212 StrictMode.enableDeathOnNetwork();
3213 }
3214
3215 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003216 * Switch this process to density compatibility mode if needed.
3217 */
3218 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3219 == 0) {
3220 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3221 }
Bob Leee5408332009-09-04 18:31:17 -07003222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3224 // XXX should have option to change the port.
3225 Debug.changeDebugPort(8100);
3226 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003227 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 + " is waiting for the debugger on port 8100...");
3229
3230 IActivityManager mgr = ActivityManagerNative.getDefault();
3231 try {
3232 mgr.showWaitingForDebugger(mAppThread, true);
3233 } catch (RemoteException ex) {
3234 }
3235
3236 Debug.waitForDebugger();
3237
3238 try {
3239 mgr.showWaitingForDebugger(mAppThread, false);
3240 } catch (RemoteException ex) {
3241 }
3242
3243 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003244 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 + " can be debugged on port 8100...");
3246 }
3247 }
3248
3249 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003250 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 appContext.init(data.info, null, this);
3252 InstrumentationInfo ii = null;
3253 try {
3254 ii = appContext.getPackageManager().
3255 getInstrumentationInfo(data.instrumentationName, 0);
3256 } catch (PackageManager.NameNotFoundException e) {
3257 }
3258 if (ii == null) {
3259 throw new RuntimeException(
3260 "Unable to find instrumentation info for: "
3261 + data.instrumentationName);
3262 }
3263
3264 mInstrumentationAppDir = ii.sourceDir;
3265 mInstrumentationAppPackage = ii.packageName;
3266 mInstrumentedAppDir = data.info.getAppDir();
3267
3268 ApplicationInfo instrApp = new ApplicationInfo();
3269 instrApp.packageName = ii.packageName;
3270 instrApp.sourceDir = ii.sourceDir;
3271 instrApp.publicSourceDir = ii.publicSourceDir;
3272 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003273 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003274 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003276 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 instrContext.init(pi, null, this);
3278
3279 try {
3280 java.lang.ClassLoader cl = instrContext.getClassLoader();
3281 mInstrumentation = (Instrumentation)
3282 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3283 } catch (Exception e) {
3284 throw new RuntimeException(
3285 "Unable to instantiate instrumentation "
3286 + data.instrumentationName + ": " + e.toString(), e);
3287 }
3288
3289 mInstrumentation.init(this, instrContext, appContext,
3290 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3291
3292 if (data.profileFile != null && !ii.handleProfiling) {
3293 data.handlingProfiling = true;
3294 File file = new File(data.profileFile);
3295 file.getParentFile().mkdirs();
3296 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3297 }
3298
3299 try {
3300 mInstrumentation.onCreate(data.instrumentationArgs);
3301 }
3302 catch (Exception e) {
3303 throw new RuntimeException(
3304 "Exception thrown in onCreate() of "
3305 + data.instrumentationName + ": " + e.toString(), e);
3306 }
3307
3308 } else {
3309 mInstrumentation = new Instrumentation();
3310 }
3311
Christopher Tate181fafa2009-05-14 11:12:14 -07003312 // If the app is being launched for full backup or restore, bring it up in
3313 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003314 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 mInitialApplication = app;
3316
3317 List<ProviderInfo> providers = data.providers;
3318 if (providers != null) {
3319 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003320 // For process that contain content providers, we want to
3321 // ensure that the JIT is enabled "at some point".
3322 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 }
3324
3325 try {
3326 mInstrumentation.callApplicationOnCreate(app);
3327 } catch (Exception e) {
3328 if (!mInstrumentation.onException(app, e)) {
3329 throw new RuntimeException(
3330 "Unable to create application " + app.getClass().getName()
3331 + ": " + e.toString(), e);
3332 }
3333 }
3334 }
3335
3336 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3337 IActivityManager am = ActivityManagerNative.getDefault();
3338 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3339 Debug.stopMethodTracing();
3340 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003341 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 // + ", app thr: " + mAppThread);
3343 try {
3344 am.finishInstrumentation(mAppThread, resultCode, results);
3345 } catch (RemoteException ex) {
3346 }
3347 }
3348
3349 private final void installContentProviders(
3350 Context context, List<ProviderInfo> providers) {
3351 final ArrayList<IActivityManager.ContentProviderHolder> results =
3352 new ArrayList<IActivityManager.ContentProviderHolder>();
3353
3354 Iterator<ProviderInfo> i = providers.iterator();
3355 while (i.hasNext()) {
3356 ProviderInfo cpi = i.next();
3357 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003358 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 buf.append(cpi.authority);
3360 buf.append(": ");
3361 buf.append(cpi.name);
3362 Log.i(TAG, buf.toString());
3363 IContentProvider cp = installProvider(context, null, cpi, false);
3364 if (cp != null) {
3365 IActivityManager.ContentProviderHolder cph =
3366 new IActivityManager.ContentProviderHolder(cpi);
3367 cph.provider = cp;
3368 results.add(cph);
3369 // Don't ever unload this provider from the process.
3370 synchronized(mProviderMap) {
3371 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3372 }
3373 }
3374 }
3375
3376 try {
3377 ActivityManagerNative.getDefault().publishContentProviders(
3378 getApplicationThread(), results);
3379 } catch (RemoteException ex) {
3380 }
3381 }
3382
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003383 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003385 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 if (pr != null) {
3387 return pr.mProvider;
3388 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003389 return null;
3390 }
3391 }
3392
3393 private final IContentProvider getProvider(Context context, String name) {
3394 IContentProvider existing = getExistingProvider(context, name);
3395 if (existing != null) {
3396 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 }
3398
3399 IActivityManager.ContentProviderHolder holder = null;
3400 try {
3401 holder = ActivityManagerNative.getDefault().getContentProvider(
3402 getApplicationThread(), name);
3403 } catch (RemoteException ex) {
3404 }
3405 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003406 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 return null;
3408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409
3410 IContentProvider prov = installProvider(context, holder.provider,
3411 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003412 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 if (holder.noReleaseNeeded || holder.provider == null) {
3414 // We are not going to release the provider if it is an external
3415 // provider that doesn't care about being released, or if it is
3416 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003417 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 synchronized(mProviderMap) {
3419 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3420 }
3421 }
3422 return prov;
3423 }
3424
3425 public final IContentProvider acquireProvider(Context c, String name) {
3426 IContentProvider provider = getProvider(c, name);
3427 if(provider == null)
3428 return null;
3429 IBinder jBinder = provider.asBinder();
3430 synchronized(mProviderMap) {
3431 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3432 if(prc == null) {
3433 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3434 } else {
3435 prc.count++;
3436 } //end else
3437 } //end synchronized
3438 return provider;
3439 }
3440
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003441 public final IContentProvider acquireExistingProvider(Context c, String name) {
3442 IContentProvider provider = getExistingProvider(c, name);
3443 if(provider == null)
3444 return null;
3445 IBinder jBinder = provider.asBinder();
3446 synchronized(mProviderMap) {
3447 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3448 if(prc == null) {
3449 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3450 } else {
3451 prc.count++;
3452 } //end else
3453 } //end synchronized
3454 return provider;
3455 }
3456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 public final boolean releaseProvider(IContentProvider provider) {
3458 if(provider == null) {
3459 return false;
3460 }
3461 IBinder jBinder = provider.asBinder();
3462 synchronized(mProviderMap) {
3463 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3464 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003465 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 return false;
3467 } else {
3468 prc.count--;
3469 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003470 // Schedule the actual remove asynchronously, since we
3471 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003472 // TODO: it would be nice to post a delayed message, so
3473 // if we come back and need the same provider quickly
3474 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003475 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3476 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 } //end if
3478 } //end else
3479 } //end synchronized
3480 return true;
3481 }
3482
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003483 final void completeRemoveProvider(IContentProvider provider) {
3484 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003485 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003486 synchronized(mProviderMap) {
3487 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3488 if(prc != null && prc.count == 0) {
3489 mProviderRefCountMap.remove(jBinder);
3490 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003491 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003492 }
3493 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003494
3495 if (name != null) {
3496 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003497 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003498 "ActivityManagerNative.removeContentProvider(" + name);
3499 ActivityManagerNative.getDefault().removeContentProvider(
3500 getApplicationThread(), name);
3501 } catch (RemoteException e) {
3502 //do nothing content provider object is dead any way
3503 } //end catch
3504 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003505 }
3506
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003507 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003509 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 }
3511 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003513 String name = null;
3514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003516 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003518 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 IBinder myBinder = pr.mProvider.asBinder();
3520 if (myBinder == providerBinder) {
3521 //find if its published by this process itself
3522 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003523 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003524 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003526 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 "death recipient");
3528 //content provider is in another process
3529 myBinder.unlinkToDeath(pr, 0);
3530 iter.remove();
3531 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003532 if(name == null) {
3533 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 }
3535 } //end if myBinder
3536 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003537
3538 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 }
3540
3541 final void removeDeadProvider(String name, IContentProvider provider) {
3542 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003543 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003545 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003546 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003547 if (removed != null) {
3548 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 }
3551 }
3552 }
3553
3554 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003555 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003557 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003558 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003559 if (removed != null) {
3560 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 }
3563 }
3564
3565 private final IContentProvider installProvider(Context context,
3566 IContentProvider provider, ProviderInfo info, boolean noisy) {
3567 ContentProvider localProvider = null;
3568 if (provider == null) {
3569 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003570 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 + info.name);
3572 }
3573 Context c = null;
3574 ApplicationInfo ai = info.applicationInfo;
3575 if (context.getPackageName().equals(ai.packageName)) {
3576 c = context;
3577 } else if (mInitialApplication != null &&
3578 mInitialApplication.getPackageName().equals(ai.packageName)) {
3579 c = mInitialApplication;
3580 } else {
3581 try {
3582 c = context.createPackageContext(ai.packageName,
3583 Context.CONTEXT_INCLUDE_CODE);
3584 } catch (PackageManager.NameNotFoundException e) {
3585 }
3586 }
3587 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003588 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 ai.packageName +
3590 " while loading content provider " +
3591 info.name);
3592 return null;
3593 }
3594 try {
3595 final java.lang.ClassLoader cl = c.getClassLoader();
3596 localProvider = (ContentProvider)cl.
3597 loadClass(info.name).newInstance();
3598 provider = localProvider.getIContentProvider();
3599 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003600 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 info.name + " from sourceDir " +
3602 info.applicationInfo.sourceDir);
3603 return null;
3604 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003605 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606 TAG, "Instantiating local provider " + info.name);
3607 // XXX Need to create the correct context for this provider.
3608 localProvider.attachInfo(c, info);
3609 } catch (java.lang.Exception e) {
3610 if (!mInstrumentation.onException(null, e)) {
3611 throw new RuntimeException(
3612 "Unable to get provider " + info.name
3613 + ": " + e.toString(), e);
3614 }
3615 return null;
3616 }
3617 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003618 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 + info.name);
3620 }
3621
3622 synchronized (mProviderMap) {
3623 // Cache the pointer for the remote provider.
3624 String names[] = PATTERN_SEMICOLON.split(info.authority);
3625 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003626 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 localProvider);
3628 try {
3629 provider.asBinder().linkToDeath(pr, 0);
3630 mProviderMap.put(names[i], pr);
3631 } catch (RemoteException e) {
3632 return null;
3633 }
3634 }
3635 if (localProvider != null) {
3636 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003637 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 }
3639 }
3640
3641 return provider;
3642 }
3643
3644 private final void attach(boolean system) {
3645 sThreadLocal.set(this);
3646 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003648 ViewRoot.addFirstDrawHandler(new Runnable() {
3649 public void run() {
3650 ensureJitEnabled();
3651 }
3652 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3654 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3655 IActivityManager mgr = ActivityManagerNative.getDefault();
3656 try {
3657 mgr.attachApplication(mAppThread);
3658 } catch (RemoteException ex) {
3659 }
3660 } else {
3661 // Don't set application object here -- if the system crashes,
3662 // we can't display an alert, we just want to die die die.
3663 android.ddm.DdmHandleAppName.setAppName("system_process");
3664 try {
3665 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003666 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 context.init(getSystemContext().mPackageInfo, null, this);
3668 Application app = Instrumentation.newApplication(Application.class, context);
3669 mAllApplications.add(app);
3670 mInitialApplication = app;
3671 app.onCreate();
3672 } catch (Exception e) {
3673 throw new RuntimeException(
3674 "Unable to instantiate Application():" + e.toString(), e);
3675 }
3676 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003677
3678 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3679 public void onConfigurationChanged(Configuration newConfig) {
3680 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003681 // We need to apply this change to the resources
3682 // immediately, because upon returning the view
3683 // hierarchy will be informed about it.
3684 if (applyConfigurationToResourcesLocked(newConfig)) {
3685 // This actually changed the resources! Tell
3686 // everyone about it.
3687 if (mPendingConfiguration == null ||
3688 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3689 mPendingConfiguration = newConfig;
3690
3691 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3692 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003693 }
3694 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003695 }
3696 public void onLowMemory() {
3697 }
3698 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 }
3700
3701 private final void detach()
3702 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 sThreadLocal.set(null);
3704 }
3705
3706 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003707 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 ActivityThread thread = new ActivityThread();
3709 thread.attach(true);
3710 return thread;
3711 }
3712
3713 public final void installSystemProviders(List providers) {
3714 if (providers != null) {
3715 installContentProviders(mInitialApplication,
3716 (List<ProviderInfo>)providers);
3717 }
3718 }
3719
3720 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003721 SamplingProfilerIntegration.start();
3722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 Process.setArgV0("<pre-initialized>");
3724
3725 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003726 if (sMainThreadHandler == null) {
3727 sMainThreadHandler = new Handler();
3728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729
3730 ActivityThread thread = new ActivityThread();
3731 thread.attach(false);
3732
Dianne Hackborn287952c2010-09-22 22:34:31 -07003733 if (false) {
3734 Looper.myLooper().setMessageLogging(new
3735 LogPrinter(Log.DEBUG, "ActivityThread"));
3736 }
3737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 Looper.loop();
3739
3740 if (Process.supportsProcesses()) {
3741 throw new RuntimeException("Main thread loop unexpectedly exited");
3742 }
3743
3744 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003745 String name = (thread.mInitialApplication != null)
3746 ? thread.mInitialApplication.getPackageName()
3747 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003748 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 }
3750}