blob: 7315f01c8b1e1f39c78322f164186d31d55f4f81 [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
1784 private final void handleReceiver(ReceiverData data) {
1785 // If we are getting ready to gc after going to the background, well
1786 // we are back active so skip it.
1787 unscheduleGcIdler();
1788
1789 String component = data.intent.getComponent().getClassName();
1790
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001791 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 data.info.applicationInfo);
1793
1794 IActivityManager mgr = ActivityManagerNative.getDefault();
1795
1796 BroadcastReceiver receiver = null;
1797 try {
1798 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1799 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001800 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1802 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001803 if (DEBUG_BROADCAST) Slog.i(TAG,
1804 "Finishing failed broadcast to " + data.intent.getComponent());
1805 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 throw new RuntimeException(
1807 "Unable to instantiate receiver " + component
1808 + ": " + e.toString(), e);
1809 }
1810
1811 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001812 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001813
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001814 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 TAG, "Performing receive of " + data.intent
1816 + ": app=" + app
1817 + ", appName=" + app.getPackageName()
1818 + ", pkg=" + packageInfo.getPackageName()
1819 + ", comp=" + data.intent.getComponent().toShortString()
1820 + ", dir=" + packageInfo.getAppDir());
1821
Dianne Hackborn21556372010-02-04 16:34:40 -08001822 ContextImpl context = (ContextImpl)app.getBaseContext();
Dianne Hackborne829fef2010-10-26 17:44:01 -07001823 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 receiver.onReceive(context.getReceiverRestrictedContext(),
1825 data.intent);
1826 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001827 if (DEBUG_BROADCAST) Slog.i(TAG,
1828 "Finishing failed broadcast to " + data.intent.getComponent());
1829 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 if (!mInstrumentation.onException(receiver, e)) {
1831 throw new RuntimeException(
1832 "Unable to start receiver " + component
1833 + ": " + e.toString(), e);
1834 }
1835 }
1836
Dianne Hackborne829fef2010-10-26 17:44:01 -07001837 if (receiver.getPendingResult() != null) {
1838 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
1840 }
1841
Christopher Tate181fafa2009-05-14 11:12:14 -07001842 // Instantiate a BackupAgent and tell it that it's alive
1843 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001844 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001845
1846 // no longer idle; we have backup work to do
1847 unscheduleGcIdler();
1848
1849 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001850 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001851 String packageName = packageInfo.mPackageName;
1852 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001853 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001854 + " already exists");
1855 return;
1856 }
Bob Leee5408332009-09-04 18:31:17 -07001857
Christopher Tate181fafa2009-05-14 11:12:14 -07001858 BackupAgent agent = null;
1859 String classname = data.appInfo.backupAgentName;
1860 if (classname == null) {
1861 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001862 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001863 + packageName);
1864 return;
1865 }
1866 classname = "android.app.FullBackupAgent";
1867 }
1868 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001869 IBinder binder = null;
1870 try {
1871 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1872 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1873
1874 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001875 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001876 + data.appInfo.backupAgentName);
1877
Dianne Hackborn21556372010-02-04 16:34:40 -08001878 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001879 context.init(packageInfo, null, this);
1880 context.setOuterContext(agent);
1881 agent.attach(context);
1882
1883 agent.onCreate();
1884 binder = agent.onBind();
1885 mBackupAgents.put(packageName, agent);
1886 } catch (Exception e) {
1887 // If this is during restore, fail silently; otherwise go
1888 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001889 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001890 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1891 throw e;
1892 }
1893 // falling through with 'binder' still null
1894 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001895
1896 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001897 try {
1898 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1899 } catch (RemoteException e) {
1900 // nothing to do.
1901 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001902 } catch (Exception e) {
1903 throw new RuntimeException("Unable to create BackupAgent "
1904 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1905 }
1906 }
1907
1908 // Tear down a BackupAgent
1909 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001910 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001911
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001912 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001913 String packageName = packageInfo.mPackageName;
1914 BackupAgent agent = mBackupAgents.get(packageName);
1915 if (agent != null) {
1916 try {
1917 agent.onDestroy();
1918 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001919 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001920 e.printStackTrace();
1921 }
1922 mBackupAgents.remove(packageName);
1923 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001924 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001925 }
1926 }
1927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 private final void handleCreateService(CreateServiceData data) {
1929 // If we are getting ready to gc after going to the background, well
1930 // we are back active so skip it.
1931 unscheduleGcIdler();
1932
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001933 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 data.info.applicationInfo);
1935 Service service = null;
1936 try {
1937 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1938 service = (Service) cl.loadClass(data.info.name).newInstance();
1939 } catch (Exception e) {
1940 if (!mInstrumentation.onException(service, e)) {
1941 throw new RuntimeException(
1942 "Unable to instantiate service " + data.info.name
1943 + ": " + e.toString(), e);
1944 }
1945 }
1946
1947 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001948 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949
Dianne Hackborn21556372010-02-04 16:34:40 -08001950 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 context.init(packageInfo, null, this);
1952
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001953 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 context.setOuterContext(service);
1955 service.attach(context, this, data.info.name, data.token, app,
1956 ActivityManagerNative.getDefault());
1957 service.onCreate();
1958 mServices.put(data.token, service);
1959 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001960 ActivityManagerNative.getDefault().serviceDoneExecuting(
1961 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 } catch (RemoteException e) {
1963 // nothing to do.
1964 }
1965 } catch (Exception e) {
1966 if (!mInstrumentation.onException(service, e)) {
1967 throw new RuntimeException(
1968 "Unable to create service " + data.info.name
1969 + ": " + e.toString(), e);
1970 }
1971 }
1972 }
1973
1974 private final void handleBindService(BindServiceData data) {
1975 Service s = mServices.get(data.token);
1976 if (s != null) {
1977 try {
1978 data.intent.setExtrasClassLoader(s.getClassLoader());
1979 try {
1980 if (!data.rebind) {
1981 IBinder binder = s.onBind(data.intent);
1982 ActivityManagerNative.getDefault().publishService(
1983 data.token, data.intent, binder);
1984 } else {
1985 s.onRebind(data.intent);
1986 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001987 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001989 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 } catch (RemoteException ex) {
1991 }
1992 } catch (Exception e) {
1993 if (!mInstrumentation.onException(s, e)) {
1994 throw new RuntimeException(
1995 "Unable to bind to service " + s
1996 + " with " + data.intent + ": " + e.toString(), e);
1997 }
1998 }
1999 }
2000 }
2001
2002 private final void handleUnbindService(BindServiceData data) {
2003 Service s = mServices.get(data.token);
2004 if (s != null) {
2005 try {
2006 data.intent.setExtrasClassLoader(s.getClassLoader());
2007 boolean doRebind = s.onUnbind(data.intent);
2008 try {
2009 if (doRebind) {
2010 ActivityManagerNative.getDefault().unbindFinished(
2011 data.token, data.intent, doRebind);
2012 } else {
2013 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002014 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 }
2016 } catch (RemoteException ex) {
2017 }
2018 } catch (Exception e) {
2019 if (!mInstrumentation.onException(s, e)) {
2020 throw new RuntimeException(
2021 "Unable to unbind to service " + s
2022 + " with " + data.intent + ": " + e.toString(), e);
2023 }
2024 }
2025 }
2026 }
2027
Dianne Hackborn625ac272010-09-17 18:29:22 -07002028 private void handleDumpService(DumpComponentInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002030 Service s = mServices.get(info.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 if (s != null) {
2032 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2033 s.dump(info.fd, pw, info.args);
2034 pw.close();
2035 }
2036 } finally {
2037 synchronized (info) {
2038 info.dumped = true;
2039 info.notifyAll();
2040 }
2041 }
2042 }
2043
Dianne Hackborn625ac272010-09-17 18:29:22 -07002044 private void handleDumpActivity(DumpComponentInfo info) {
2045 try {
2046 ActivityClientRecord r = mActivities.get(info.token);
2047 if (r != null && r.activity != null) {
2048 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2049 r.activity.dump(info.fd, pw, info.args);
2050 pw.close();
2051 }
2052 } finally {
2053 synchronized (info) {
2054 info.dumped = true;
2055 info.notifyAll();
2056 }
2057 }
2058 }
2059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 private final void handleServiceArgs(ServiceArgsData data) {
2061 Service s = mServices.get(data.token);
2062 if (s != null) {
2063 try {
2064 if (data.args != null) {
2065 data.args.setExtrasClassLoader(s.getClassLoader());
2066 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002067 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002068
2069 QueuedWork.waitToFinish();
2070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002072 ActivityManagerNative.getDefault().serviceDoneExecuting(
2073 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 } catch (RemoteException e) {
2075 // nothing to do.
2076 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002077 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 } catch (Exception e) {
2079 if (!mInstrumentation.onException(s, e)) {
2080 throw new RuntimeException(
2081 "Unable to start service " + s
2082 + " with " + data.args + ": " + e.toString(), e);
2083 }
2084 }
2085 }
2086 }
2087
2088 private final void handleStopService(IBinder token) {
2089 Service s = mServices.remove(token);
2090 if (s != null) {
2091 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002092 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 s.onDestroy();
2094 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002095 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002097 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002099
2100 QueuedWork.waitToFinish();
2101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002103 ActivityManagerNative.getDefault().serviceDoneExecuting(
2104 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 } catch (RemoteException e) {
2106 // nothing to do.
2107 }
2108 } catch (Exception e) {
2109 if (!mInstrumentation.onException(s, e)) {
2110 throw new RuntimeException(
2111 "Unable to stop service " + s
2112 + ": " + e.toString(), e);
2113 }
2114 }
2115 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002116 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 }
2118
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002119 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002121 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002122 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 + " finished=" + r.activity.mFinished);
2124 if (r != null && !r.activity.mFinished) {
2125 if (clearHide) {
2126 r.hideForNow = false;
2127 r.activity.mStartedActivity = false;
2128 }
2129 try {
2130 if (r.pendingIntents != null) {
2131 deliverNewIntents(r, r.pendingIntents);
2132 r.pendingIntents = null;
2133 }
2134 if (r.pendingResults != null) {
2135 deliverResults(r, r.pendingResults);
2136 r.pendingResults = null;
2137 }
2138 r.activity.performResume();
2139
Bob Leee5408332009-09-04 18:31:17 -07002140 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 r.paused = false;
2144 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 r.state = null;
2146 } catch (Exception e) {
2147 if (!mInstrumentation.onException(r.activity, e)) {
2148 throw new RuntimeException(
2149 "Unable to resume activity "
2150 + r.intent.getComponent().toShortString()
2151 + ": " + e.toString(), e);
2152 }
2153 }
2154 }
2155 return r;
2156 }
2157
2158 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2159 // If we are getting ready to gc after going to the background, well
2160 // we are back active so skip it.
2161 unscheduleGcIdler();
2162
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002163 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164
2165 if (r != null) {
2166 final Activity a = r.activity;
2167
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002168 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 TAG, "Resume " + r + " started activity: " +
2170 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2171 + ", finished: " + a.mFinished);
2172
2173 final int forwardBit = isForward ?
2174 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 // If the window hasn't yet been added to the window manager,
2177 // and this guy didn't finish itself or start another activity,
2178 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002179 boolean willBeVisible = !a.mStartedActivity;
2180 if (!willBeVisible) {
2181 try {
2182 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2183 a.getActivityToken());
2184 } catch (RemoteException e) {
2185 }
2186 }
2187 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 r.window = r.activity.getWindow();
2189 View decor = r.window.getDecorView();
2190 decor.setVisibility(View.INVISIBLE);
2191 ViewManager wm = a.getWindowManager();
2192 WindowManager.LayoutParams l = r.window.getAttributes();
2193 a.mDecor = decor;
2194 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2195 l.softInputMode |= forwardBit;
2196 if (a.mVisibleFromClient) {
2197 a.mWindowAdded = true;
2198 wm.addView(decor, l);
2199 }
2200
2201 // If the window has already been added, but during resume
2202 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002203 // window visible.
2204 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002205 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 TAG, "Launch " + r + " mStartedActivity set");
2207 r.hideForNow = true;
2208 }
2209
2210 // The window is now visible if it has been added, we are not
2211 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002212 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002213 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002215 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002216 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 performConfigurationChanged(r.activity, r.newConfig);
2218 r.newConfig = null;
2219 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002220 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 + isForward);
2222 WindowManager.LayoutParams l = r.window.getAttributes();
2223 if ((l.softInputMode
2224 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2225 != forwardBit) {
2226 l.softInputMode = (l.softInputMode
2227 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2228 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002229 if (r.activity.mVisibleFromClient) {
2230 ViewManager wm = a.getWindowManager();
2231 View decor = r.window.getDecorView();
2232 wm.updateViewLayout(decor, l);
2233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 }
2235 r.activity.mVisibleFromServer = true;
2236 mNumVisibleActivities++;
2237 if (r.activity.mVisibleFromClient) {
2238 r.activity.makeVisible();
2239 }
2240 }
2241
2242 r.nextIdle = mNewActivities;
2243 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002244 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 TAG, "Scheduling idle handler for " + r);
2246 Looper.myQueue().addIdleHandler(new Idler());
2247
2248 } else {
2249 // If an exception was thrown when trying to resume, then
2250 // just end this activity.
2251 try {
2252 ActivityManagerNative.getDefault()
2253 .finishActivity(token, Activity.RESULT_CANCELED, null);
2254 } catch (RemoteException ex) {
2255 }
2256 }
2257 }
2258
2259 private int mThumbnailWidth = -1;
2260 private int mThumbnailHeight = -1;
2261
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002262 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 Bitmap thumbnail = null;
2264 try {
2265 int w = mThumbnailWidth;
2266 int h;
2267 if (w < 0) {
2268 Resources res = r.activity.getResources();
2269 mThumbnailHeight = h =
2270 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2271
2272 mThumbnailWidth = w =
2273 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2274 } else {
2275 h = mThumbnailHeight;
2276 }
2277
Jim Miller0b2a6d02010-07-13 18:01:29 -07002278 // On platforms where we don't want thumbnails, set dims to (0,0)
2279 if ((w > 0) && (h > 0)) {
2280 View topView = r.activity.getWindow().getDecorView();
2281
2282 // Maximize bitmap by capturing in native aspect.
2283 if (topView.getWidth() >= topView.getHeight()) {
2284 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2285 } else {
2286 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2287 }
2288
2289 thumbnail.eraseColor(0);
2290 Canvas cv = new Canvas(thumbnail);
2291 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2292 thumbnail = null;
2293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 } catch (Exception e) {
2297 if (!mInstrumentation.onException(r.activity, e)) {
2298 throw new RuntimeException(
2299 "Unable to create thumbnail of "
2300 + r.intent.getComponent().toShortString()
2301 + ": " + e.toString(), e);
2302 }
2303 thumbnail = null;
2304 }
2305
2306 return thumbnail;
2307 }
2308
2309 private final void handlePauseActivity(IBinder token, boolean finished,
2310 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002311 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002313 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 if (userLeaving) {
2315 performUserLeavingActivity(r);
2316 }
Bob Leee5408332009-09-04 18:31:17 -07002317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 r.activity.mConfigChangeFlags |= configChanges;
2319 Bundle state = performPauseActivity(token, finished, true);
2320
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002321 // Make sure any pending writes are now committed.
2322 QueuedWork.waitToFinish();
2323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 // Tell the activity manager we have paused.
2325 try {
2326 ActivityManagerNative.getDefault().activityPaused(token, state);
2327 } catch (RemoteException ex) {
2328 }
2329 }
2330 }
2331
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002332 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 mInstrumentation.callActivityOnUserLeaving(r.activity);
2334 }
2335
2336 final Bundle performPauseActivity(IBinder token, boolean finished,
2337 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002338 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 return r != null ? performPauseActivity(r, finished, saveState) : null;
2340 }
2341
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002342 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 boolean saveState) {
2344 if (r.paused) {
2345 if (r.activity.mFinished) {
2346 // If we are finishing, we won't call onResume() in certain cases.
2347 // So here we likewise don't want to call onPause() if the activity
2348 // isn't resumed.
2349 return null;
2350 }
2351 RuntimeException e = new RuntimeException(
2352 "Performing pause of activity that is not resumed: "
2353 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002354 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 }
2356 Bundle state = null;
2357 if (finished) {
2358 r.activity.mFinished = true;
2359 }
2360 try {
2361 // Next have the activity save its current state and managed dialogs...
2362 if (!r.activity.mFinished && saveState) {
2363 state = new Bundle();
2364 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2365 r.state = state;
2366 }
2367 // Now we are idle.
2368 r.activity.mCalled = false;
2369 mInstrumentation.callActivityOnPause(r.activity);
2370 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2371 if (!r.activity.mCalled) {
2372 throw new SuperNotCalledException(
2373 "Activity " + r.intent.getComponent().toShortString() +
2374 " did not call through to super.onPause()");
2375 }
2376
2377 } catch (SuperNotCalledException e) {
2378 throw e;
2379
2380 } catch (Exception e) {
2381 if (!mInstrumentation.onException(r.activity, e)) {
2382 throw new RuntimeException(
2383 "Unable to pause activity "
2384 + r.intent.getComponent().toShortString()
2385 + ": " + e.toString(), e);
2386 }
2387 }
2388 r.paused = true;
2389 return state;
2390 }
2391
2392 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002393 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 performStopActivityInner(r, null, false);
2395 }
2396
2397 private static class StopInfo {
2398 Bitmap thumbnail;
2399 CharSequence description;
2400 }
2401
2402 private final class ProviderRefCount {
2403 public int count;
2404 ProviderRefCount(int pCount) {
2405 count = pCount;
2406 }
2407 }
2408
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002409 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002411 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 if (r != null) {
2413 if (!keepShown && r.stopped) {
2414 if (r.activity.mFinished) {
2415 // If we are finishing, we won't call onResume() in certain
2416 // cases. So here we likewise don't want to call onStop()
2417 // if the activity isn't resumed.
2418 return;
2419 }
2420 RuntimeException e = new RuntimeException(
2421 "Performing stop of activity that is not resumed: "
2422 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002423 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 }
2425
2426 if (info != null) {
2427 try {
2428 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002429 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 info.description = r.activity.onCreateDescription();
2431 } catch (Exception e) {
2432 if (!mInstrumentation.onException(r.activity, e)) {
2433 throw new RuntimeException(
2434 "Unable to save state of activity "
2435 + r.intent.getComponent().toShortString()
2436 + ": " + e.toString(), e);
2437 }
2438 }
2439 }
2440
2441 if (!keepShown) {
2442 try {
2443 // Now we are idle.
2444 r.activity.performStop();
2445 } catch (Exception e) {
2446 if (!mInstrumentation.onException(r.activity, e)) {
2447 throw new RuntimeException(
2448 "Unable to stop activity "
2449 + r.intent.getComponent().toShortString()
2450 + ": " + e.toString(), e);
2451 }
2452 }
2453 r.stopped = true;
2454 }
2455
2456 r.paused = true;
2457 }
2458 }
2459
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002460 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 View v = r.activity.mDecor;
2462 if (v != null) {
2463 if (show) {
2464 if (!r.activity.mVisibleFromServer) {
2465 r.activity.mVisibleFromServer = true;
2466 mNumVisibleActivities++;
2467 if (r.activity.mVisibleFromClient) {
2468 r.activity.makeVisible();
2469 }
2470 }
2471 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002472 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002473 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 performConfigurationChanged(r.activity, r.newConfig);
2475 r.newConfig = null;
2476 }
2477 } else {
2478 if (r.activity.mVisibleFromServer) {
2479 r.activity.mVisibleFromServer = false;
2480 mNumVisibleActivities--;
2481 v.setVisibility(View.INVISIBLE);
2482 }
2483 }
2484 }
2485 }
2486
2487 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002488 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 r.activity.mConfigChangeFlags |= configChanges;
2490
2491 StopInfo info = new StopInfo();
2492 performStopActivityInner(r, info, show);
2493
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002494 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 TAG, "Finishing stop of " + r + ": show=" + show
2496 + " win=" + r.window);
2497
2498 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 // Tell activity manager we have been stopped.
2501 try {
2502 ActivityManagerNative.getDefault().activityStopped(
2503 r.token, info.thumbnail, info.description);
2504 } catch (RemoteException ex) {
2505 }
2506 }
2507
2508 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002509 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 if (r.stopped) {
2511 r.activity.performRestart();
2512 r.stopped = false;
2513 }
2514 }
2515
2516 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002517 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 if (!show && !r.stopped) {
2519 performStopActivityInner(r, null, show);
2520 } else if (show && r.stopped) {
2521 // If we are getting ready to gc after going to the background, well
2522 // we are back active so skip it.
2523 unscheduleGcIdler();
2524
2525 r.activity.performRestart();
2526 r.stopped = false;
2527 }
2528 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002529 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 TAG, "Handle window " + r + " visibility: " + show);
2531 updateVisibility(r, show);
2532 }
2533 }
2534
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002535 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 final int N = results.size();
2537 for (int i=0; i<N; i++) {
2538 ResultInfo ri = results.get(i);
2539 try {
2540 if (ri.mData != null) {
2541 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2542 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002543 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002544 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 r.activity.dispatchActivityResult(ri.mResultWho,
2546 ri.mRequestCode, ri.mResultCode, ri.mData);
2547 } catch (Exception e) {
2548 if (!mInstrumentation.onException(r.activity, e)) {
2549 throw new RuntimeException(
2550 "Failure delivering result " + ri + " to activity "
2551 + r.intent.getComponent().toShortString()
2552 + ": " + e.toString(), e);
2553 }
2554 }
2555 }
2556 }
2557
2558 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002559 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002560 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 if (r != null) {
2562 final boolean resumed = !r.paused;
2563 if (!r.activity.mFinished && r.activity.mDecor != null
2564 && r.hideForNow && resumed) {
2565 // We had hidden the activity because it started another
2566 // one... we have gotten a result back and we are not
2567 // paused, so make sure our window is visible.
2568 updateVisibility(r, true);
2569 }
2570 if (resumed) {
2571 try {
2572 // Now we are idle.
2573 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002574 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 mInstrumentation.callActivityOnPause(r.activity);
2576 if (!r.activity.mCalled) {
2577 throw new SuperNotCalledException(
2578 "Activity " + r.intent.getComponent().toShortString()
2579 + " did not call through to super.onPause()");
2580 }
2581 } catch (SuperNotCalledException e) {
2582 throw e;
2583 } catch (Exception e) {
2584 if (!mInstrumentation.onException(r.activity, e)) {
2585 throw new RuntimeException(
2586 "Unable to pause activity "
2587 + r.intent.getComponent().toShortString()
2588 + ": " + e.toString(), e);
2589 }
2590 }
2591 }
2592 deliverResults(r, res.results);
2593 if (resumed) {
2594 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002595 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 }
2597 }
2598 }
2599
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002600 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 return performDestroyActivity(token, finishing, 0, false);
2602 }
2603
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002604 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002606 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002607 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 if (r != null) {
2609 r.activity.mConfigChangeFlags |= configChanges;
2610 if (finishing) {
2611 r.activity.mFinished = true;
2612 }
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05002613 if (getNonConfigInstance) {
2614 r.activity.mChangingConfigurations = true;
2615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 if (!r.paused) {
2617 try {
2618 r.activity.mCalled = false;
2619 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002620 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 r.activity.getComponentName().getClassName());
2622 if (!r.activity.mCalled) {
2623 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002624 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 + " did not call through to super.onPause()");
2626 }
2627 } catch (SuperNotCalledException e) {
2628 throw e;
2629 } catch (Exception e) {
2630 if (!mInstrumentation.onException(r.activity, e)) {
2631 throw new RuntimeException(
2632 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002633 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 + ": " + e.toString(), e);
2635 }
2636 }
2637 r.paused = true;
2638 }
2639 if (!r.stopped) {
2640 try {
2641 r.activity.performStop();
2642 } catch (SuperNotCalledException e) {
2643 throw e;
2644 } catch (Exception e) {
2645 if (!mInstrumentation.onException(r.activity, e)) {
2646 throw new RuntimeException(
2647 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002648 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 + ": " + e.toString(), e);
2650 }
2651 }
2652 r.stopped = true;
2653 }
2654 if (getNonConfigInstance) {
2655 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002656 r.lastNonConfigurationInstances
2657 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 } catch (Exception e) {
2659 if (!mInstrumentation.onException(r.activity, e)) {
2660 throw new RuntimeException(
2661 "Unable to retain activity "
2662 + r.intent.getComponent().toShortString()
2663 + ": " + e.toString(), e);
2664 }
2665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 }
2667 try {
2668 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002669 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 if (!r.activity.mCalled) {
2671 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002672 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 " did not call through to super.onDestroy()");
2674 }
2675 if (r.window != null) {
2676 r.window.closeAllPanels();
2677 }
2678 } catch (SuperNotCalledException e) {
2679 throw e;
2680 } catch (Exception e) {
2681 if (!mInstrumentation.onException(r.activity, e)) {
2682 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002683 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2684 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 }
2686 }
2687 }
2688 mActivities.remove(token);
2689
2690 return r;
2691 }
2692
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002693 private static String safeToComponentShortString(Intent intent) {
2694 ComponentName component = intent.getComponent();
2695 return component == null ? "[Unknown]" : component.toShortString();
2696 }
2697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 private final void handleDestroyActivity(IBinder token, boolean finishing,
2699 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002700 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 configChanges, getNonConfigInstance);
2702 if (r != null) {
2703 WindowManager wm = r.activity.getWindowManager();
2704 View v = r.activity.mDecor;
2705 if (v != null) {
2706 if (r.activity.mVisibleFromServer) {
2707 mNumVisibleActivities--;
2708 }
2709 IBinder wtoken = v.getWindowToken();
2710 if (r.activity.mWindowAdded) {
2711 wm.removeViewImmediate(v);
2712 }
2713 if (wtoken != null) {
2714 WindowManagerImpl.getDefault().closeAll(wtoken,
2715 r.activity.getClass().getName(), "Activity");
2716 }
2717 r.activity.mDecor = null;
2718 }
2719 WindowManagerImpl.getDefault().closeAll(token,
2720 r.activity.getClass().getName(), "Activity");
2721
2722 // Mocked out contexts won't be participating in the normal
2723 // process lifecycle, but if we're running with a proper
2724 // ApplicationContext we need to have it tear down things
2725 // cleanly.
2726 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002727 if (c instanceof ContextImpl) {
2728 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 r.activity.getClass().getName(), "Activity");
2730 }
2731 }
2732 if (finishing) {
2733 try {
2734 ActivityManagerNative.getDefault().activityDestroyed(token);
2735 } catch (RemoteException ex) {
2736 // If the system process has died, it's game over for everyone.
2737 }
2738 }
2739 }
2740
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002741 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 // If we are getting ready to gc after going to the background, well
2743 // we are back active so skip it.
2744 unscheduleGcIdler();
2745
2746 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002747
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002748 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002749 + tmp.token + " with configChanges=0x"
2750 + Integer.toHexString(configChanges));
2751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 // First: make sure we have the most recent configuration and most
2753 // recent version of the activity, or skip it if some previous call
2754 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002755 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 int N = mRelaunchingActivities.size();
2757 IBinder token = tmp.token;
2758 tmp = null;
2759 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002760 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 if (r.token == token) {
2762 tmp = r;
2763 mRelaunchingActivities.remove(i);
2764 i--;
2765 N--;
2766 }
2767 }
Bob Leee5408332009-09-04 18:31:17 -07002768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002770 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 return;
2772 }
Bob Leee5408332009-09-04 18:31:17 -07002773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 if (mPendingConfiguration != null) {
2775 changedConfig = mPendingConfiguration;
2776 mPendingConfiguration = null;
2777 }
2778 }
Bob Leee5408332009-09-04 18:31:17 -07002779
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002780 if (tmp.createdConfig != null) {
2781 // If the activity manager is passing us its current config,
2782 // assume that is really what we want regardless of what we
2783 // may have pending.
2784 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002785 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2786 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2787 if (changedConfig == null
2788 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2789 changedConfig = tmp.createdConfig;
2790 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002791 }
2792 }
2793
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002794 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002795 + tmp.token + ": changedConfig=" + changedConfig);
2796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 // If there was a pending configuration change, execute it first.
2798 if (changedConfig != null) {
2799 handleConfigurationChanged(changedConfig);
2800 }
Bob Leee5408332009-09-04 18:31:17 -07002801
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002802 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002803 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 if (r == null) {
2805 return;
2806 }
Bob Leee5408332009-09-04 18:31:17 -07002807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002809 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 Bundle savedState = null;
2812 if (!r.paused) {
2813 savedState = performPauseActivity(r.token, false, true);
2814 }
Bob Leee5408332009-09-04 18:31:17 -07002815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 r.activity = null;
2819 r.window = null;
2820 r.hideForNow = false;
2821 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002822 // Merge any pending results and pending intents; don't just replace them
2823 if (tmp.pendingResults != null) {
2824 if (r.pendingResults == null) {
2825 r.pendingResults = tmp.pendingResults;
2826 } else {
2827 r.pendingResults.addAll(tmp.pendingResults);
2828 }
2829 }
2830 if (tmp.pendingIntents != null) {
2831 if (r.pendingIntents == null) {
2832 r.pendingIntents = tmp.pendingIntents;
2833 } else {
2834 r.pendingIntents.addAll(tmp.pendingIntents);
2835 }
2836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 r.startsNotResumed = tmp.startsNotResumed;
2838 if (savedState != null) {
2839 r.state = savedState;
2840 }
Bob Leee5408332009-09-04 18:31:17 -07002841
Christopher Tateb70f3df2009-04-07 16:07:59 -07002842 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 }
2844
2845 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002846 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 Bitmap thumbnail = createThumbnailBitmap(r);
2848 CharSequence description = null;
2849 try {
2850 description = r.activity.onCreateDescription();
2851 } catch (Exception e) {
2852 if (!mInstrumentation.onException(r.activity, e)) {
2853 throw new RuntimeException(
2854 "Unable to create description of activity "
2855 + r.intent.getComponent().toShortString()
2856 + ": " + e.toString(), e);
2857 }
2858 }
2859 //System.out.println("Reporting top thumbnail " + thumbnail);
2860 try {
2861 ActivityManagerNative.getDefault().reportThumbnail(
2862 token, thumbnail, description);
2863 } catch (RemoteException ex) {
2864 }
2865 }
2866
2867 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2868 boolean allActivities, Configuration newConfig) {
2869 ArrayList<ComponentCallbacks> callbacks
2870 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002873 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002875 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 Activity a = ar.activity;
2877 if (a != null) {
2878 if (!ar.activity.mFinished && (allActivities ||
2879 (a != null && !ar.paused))) {
2880 // If the activity is currently resumed, its configuration
2881 // needs to change right now.
2882 callbacks.add(a);
2883 } else if (newConfig != null) {
2884 // Otherwise, we will tell it about the change
2885 // the next time it is resumed or shown. Note that
2886 // the activity manager may, before then, decide the
2887 // activity needs to be destroyed to handle its new
2888 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002889 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002890 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 ar.newConfig = newConfig;
2892 }
2893 }
2894 }
2895 }
2896 if (mServices.size() > 0) {
2897 Iterator<Service> it = mServices.values().iterator();
2898 while (it.hasNext()) {
2899 callbacks.add(it.next());
2900 }
2901 }
2902 synchronized (mProviderMap) {
2903 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002904 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 while (it.hasNext()) {
2906 callbacks.add(it.next().mLocalProvider);
2907 }
2908 }
2909 }
2910 final int N = mAllApplications.size();
2911 for (int i=0; i<N; i++) {
2912 callbacks.add(mAllApplications.get(i));
2913 }
Bob Leee5408332009-09-04 18:31:17 -07002914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 return callbacks;
2916 }
Bob Leee5408332009-09-04 18:31:17 -07002917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 private final void performConfigurationChanged(
2919 ComponentCallbacks cb, Configuration config) {
2920 // Only for Activity objects, check that they actually call up to their
2921 // superclass implementation. ComponentCallbacks is an interface, so
2922 // we check the runtime type and act accordingly.
2923 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2924 if (activity != null) {
2925 activity.mCalled = false;
2926 }
Bob Leee5408332009-09-04 18:31:17 -07002927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 boolean shouldChangeConfig = false;
2929 if ((activity == null) || (activity.mCurrentConfig == null)) {
2930 shouldChangeConfig = true;
2931 } else {
Bob Leee5408332009-09-04 18:31:17 -07002932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 // If the new config is the same as the config this Activity
2934 // is already running with then don't bother calling
2935 // onConfigurationChanged
2936 int diff = activity.mCurrentConfig.diff(config);
2937 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 // If this activity doesn't handle any of the config changes
2940 // then don't bother calling onConfigurationChanged as we're
2941 // going to destroy it.
2942 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2943 shouldChangeConfig = true;
2944 }
2945 }
2946 }
Bob Leee5408332009-09-04 18:31:17 -07002947
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002948 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002949 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 if (shouldChangeConfig) {
2951 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 if (activity != null) {
2954 if (!activity.mCalled) {
2955 throw new SuperNotCalledException(
2956 "Activity " + activity.getLocalClassName() +
2957 " did not call through to super.onConfigurationChanged()");
2958 }
2959 activity.mConfigChangeFlags = 0;
2960 activity.mCurrentConfig = new Configuration(config);
2961 }
2962 }
2963 }
2964
Dianne Hackbornae078162010-03-18 11:29:37 -07002965 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002966 if (mResConfiguration == null) {
2967 mResConfiguration = new Configuration();
2968 }
2969 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002970 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002971 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002972 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002973 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002974 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002975 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002976
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002977 // set it for java, this also affects newly created Resources
2978 if (config.locale != null) {
2979 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 }
Bob Leee5408332009-09-04 18:31:17 -07002981
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002982 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07002983
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002984 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002985 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002986
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002987 Iterator<WeakReference<Resources>> it =
2988 mActiveResources.values().iterator();
2989 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
2990 // mActiveResources.entrySet().iterator();
2991 while (it.hasNext()) {
2992 WeakReference<Resources> v = it.next();
2993 Resources r = v.get();
2994 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002995 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002996 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002997 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002998 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002999 // + " " + r + ": " + r.getConfiguration());
3000 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003001 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003002 it.remove();
3003 }
3004 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003005
3006 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003007 }
3008
3009 final void handleConfigurationChanged(Configuration config) {
3010
3011 ArrayList<ComponentCallbacks> callbacks = null;
3012
3013 synchronized (mPackages) {
3014 if (mPendingConfiguration != null) {
3015 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3016 config = mPendingConfiguration;
3017 }
3018 mPendingConfiguration = null;
3019 }
3020
3021 if (config == null) {
3022 return;
3023 }
3024
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003025 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003026 + config);
3027
3028 applyConfigurationToResourcesLocked(config);
3029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 if (mConfiguration == null) {
3031 mConfiguration = new Configuration();
3032 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003033 if (!mConfiguration.isOtherSeqNewer(config)) {
3034 return;
3035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 callbacks = collectComponentCallbacksLocked(false, config);
3039 }
Bob Leee5408332009-09-04 18:31:17 -07003040
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003041 if (callbacks != null) {
3042 final int N = callbacks.size();
3043 for (int i=0; i<N; i++) {
3044 performConfigurationChanged(callbacks.get(i), config);
3045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 }
3047 }
3048
3049 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003050 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 if (r == null || r.activity == null) {
3052 return;
3053 }
Bob Leee5408332009-09-04 18:31:17 -07003054
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003055 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003056 + r.activityInfo.name);
3057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 performConfigurationChanged(r.activity, mConfiguration);
3059 }
3060
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003061 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003062 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003063 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003064 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3065 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003066 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003067 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003068 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003069 } finally {
3070 try {
3071 pcd.fd.close();
3072 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003073 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003074 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003075 }
3076 } else {
3077 Debug.stopMethodTracing();
3078 }
3079 }
Bob Leee5408332009-09-04 18:31:17 -07003080
Andy McFadden824c5102010-07-09 16:26:57 -07003081 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3082 if (managed) {
3083 try {
3084 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3085 } catch (IOException e) {
3086 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3087 + " -- can the process access this path?");
3088 } finally {
3089 try {
3090 dhd.fd.close();
3091 } catch (IOException e) {
3092 Slog.w(TAG, "Failure closing profile fd", e);
3093 }
3094 }
3095 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003096 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003097 }
3098 }
3099
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003100 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3101 boolean hasPkgInfo = false;
3102 if (packages != null) {
3103 for (int i=packages.length-1; i>=0; i--) {
3104 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3105 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003106 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003107 ref = mPackages.get(packages[i]);
3108 if (ref != null && ref.get() != null) {
3109 hasPkgInfo = true;
3110 } else {
3111 ref = mResourcePackages.get(packages[i]);
3112 if (ref != null && ref.get() != null) {
3113 hasPkgInfo = true;
3114 }
3115 }
3116 }
3117 mPackages.remove(packages[i]);
3118 mResourcePackages.remove(packages[i]);
3119 }
3120 }
3121 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3122 hasPkgInfo);
3123 }
3124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 final void handleLowMemory() {
3126 ArrayList<ComponentCallbacks> callbacks
3127 = new ArrayList<ComponentCallbacks>();
3128
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003129 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 callbacks = collectComponentCallbacksLocked(true, null);
3131 }
Bob Leee5408332009-09-04 18:31:17 -07003132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 final int N = callbacks.size();
3134 for (int i=0; i<N; i++) {
3135 callbacks.get(i).onLowMemory();
3136 }
3137
Chris Tatece229052009-03-25 16:44:52 -07003138 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3139 if (Process.myUid() != Process.SYSTEM_UID) {
3140 int sqliteReleased = SQLiteDatabase.releaseMemory();
3141 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3142 }
Bob Leee5408332009-09-04 18:31:17 -07003143
Mike Reedcaf0df12009-04-27 14:32:05 -04003144 // Ask graphics to free up as much as possible (font/image caches)
3145 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146
3147 BinderInternal.forceGc("mem");
3148 }
3149
3150 private final void handleBindApplication(AppBindData data) {
3151 mBoundApplication = data;
3152 mConfiguration = new Configuration(data.config);
3153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003155 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 android.ddm.DdmHandleAppName.setAppName(data.processName);
3157
3158 /*
3159 * Before spawning a new process, reset the time zone to be the system time zone.
3160 * This needs to be done because the system time zone could have changed after the
3161 * the spawning of this process. Without doing this this process would have the incorrect
3162 * system time zone.
3163 */
3164 TimeZone.setDefault(null);
3165
3166 /*
3167 * Initialize the default locale in this process for the reasons we set the time zone.
3168 */
3169 Locale.setDefault(data.config.locale);
3170
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003171 /*
3172 * Update the system configuration since its preloaded and might not
3173 * reflect configuration changes. The configuration object passed
3174 * in AppBindData can be safely assumed to be up to date
3175 */
3176 Resources.getSystem().updateConfiguration(mConfiguration, null);
3177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 data.info = getPackageInfoNoCheck(data.appInfo);
3179
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003180 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003181 * For system applications on userdebug/eng builds, log stack
3182 * traces of disk and network access to dropbox for analysis.
3183 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003184 if ((data.appInfo.flags &
3185 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003186 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3187 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003188 }
3189
3190 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003191 * For apps targetting SDK Honeycomb or later, we don't allow
3192 * network usage on the main event loop / UI thread.
3193 *
3194 * Note to those grepping: this is what ultimately throws
3195 * NetworkOnMainThreadException ...
3196 */
3197 if (data.appInfo.targetSdkVersion > 9) {
3198 StrictMode.enableDeathOnNetwork();
3199 }
3200
3201 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003202 * Switch this process to density compatibility mode if needed.
3203 */
3204 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3205 == 0) {
3206 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3207 }
Bob Leee5408332009-09-04 18:31:17 -07003208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3210 // XXX should have option to change the port.
3211 Debug.changeDebugPort(8100);
3212 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003213 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 + " is waiting for the debugger on port 8100...");
3215
3216 IActivityManager mgr = ActivityManagerNative.getDefault();
3217 try {
3218 mgr.showWaitingForDebugger(mAppThread, true);
3219 } catch (RemoteException ex) {
3220 }
3221
3222 Debug.waitForDebugger();
3223
3224 try {
3225 mgr.showWaitingForDebugger(mAppThread, false);
3226 } catch (RemoteException ex) {
3227 }
3228
3229 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003230 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 + " can be debugged on port 8100...");
3232 }
3233 }
3234
3235 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003236 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 appContext.init(data.info, null, this);
3238 InstrumentationInfo ii = null;
3239 try {
3240 ii = appContext.getPackageManager().
3241 getInstrumentationInfo(data.instrumentationName, 0);
3242 } catch (PackageManager.NameNotFoundException e) {
3243 }
3244 if (ii == null) {
3245 throw new RuntimeException(
3246 "Unable to find instrumentation info for: "
3247 + data.instrumentationName);
3248 }
3249
3250 mInstrumentationAppDir = ii.sourceDir;
3251 mInstrumentationAppPackage = ii.packageName;
3252 mInstrumentedAppDir = data.info.getAppDir();
3253
3254 ApplicationInfo instrApp = new ApplicationInfo();
3255 instrApp.packageName = ii.packageName;
3256 instrApp.sourceDir = ii.sourceDir;
3257 instrApp.publicSourceDir = ii.publicSourceDir;
3258 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003259 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003260 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003262 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 instrContext.init(pi, null, this);
3264
3265 try {
3266 java.lang.ClassLoader cl = instrContext.getClassLoader();
3267 mInstrumentation = (Instrumentation)
3268 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3269 } catch (Exception e) {
3270 throw new RuntimeException(
3271 "Unable to instantiate instrumentation "
3272 + data.instrumentationName + ": " + e.toString(), e);
3273 }
3274
3275 mInstrumentation.init(this, instrContext, appContext,
3276 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3277
3278 if (data.profileFile != null && !ii.handleProfiling) {
3279 data.handlingProfiling = true;
3280 File file = new File(data.profileFile);
3281 file.getParentFile().mkdirs();
3282 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3283 }
3284
3285 try {
3286 mInstrumentation.onCreate(data.instrumentationArgs);
3287 }
3288 catch (Exception e) {
3289 throw new RuntimeException(
3290 "Exception thrown in onCreate() of "
3291 + data.instrumentationName + ": " + e.toString(), e);
3292 }
3293
3294 } else {
3295 mInstrumentation = new Instrumentation();
3296 }
3297
Christopher Tate181fafa2009-05-14 11:12:14 -07003298 // If the app is being launched for full backup or restore, bring it up in
3299 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003300 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 mInitialApplication = app;
3302
3303 List<ProviderInfo> providers = data.providers;
3304 if (providers != null) {
3305 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003306 // For process that contain content providers, we want to
3307 // ensure that the JIT is enabled "at some point".
3308 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 }
3310
3311 try {
3312 mInstrumentation.callApplicationOnCreate(app);
3313 } catch (Exception e) {
3314 if (!mInstrumentation.onException(app, e)) {
3315 throw new RuntimeException(
3316 "Unable to create application " + app.getClass().getName()
3317 + ": " + e.toString(), e);
3318 }
3319 }
3320 }
3321
3322 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3323 IActivityManager am = ActivityManagerNative.getDefault();
3324 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3325 Debug.stopMethodTracing();
3326 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003327 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 // + ", app thr: " + mAppThread);
3329 try {
3330 am.finishInstrumentation(mAppThread, resultCode, results);
3331 } catch (RemoteException ex) {
3332 }
3333 }
3334
3335 private final void installContentProviders(
3336 Context context, List<ProviderInfo> providers) {
3337 final ArrayList<IActivityManager.ContentProviderHolder> results =
3338 new ArrayList<IActivityManager.ContentProviderHolder>();
3339
3340 Iterator<ProviderInfo> i = providers.iterator();
3341 while (i.hasNext()) {
3342 ProviderInfo cpi = i.next();
3343 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003344 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 buf.append(cpi.authority);
3346 buf.append(": ");
3347 buf.append(cpi.name);
3348 Log.i(TAG, buf.toString());
3349 IContentProvider cp = installProvider(context, null, cpi, false);
3350 if (cp != null) {
3351 IActivityManager.ContentProviderHolder cph =
3352 new IActivityManager.ContentProviderHolder(cpi);
3353 cph.provider = cp;
3354 results.add(cph);
3355 // Don't ever unload this provider from the process.
3356 synchronized(mProviderMap) {
3357 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3358 }
3359 }
3360 }
3361
3362 try {
3363 ActivityManagerNative.getDefault().publishContentProviders(
3364 getApplicationThread(), results);
3365 } catch (RemoteException ex) {
3366 }
3367 }
3368
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003369 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003371 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 if (pr != null) {
3373 return pr.mProvider;
3374 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003375 return null;
3376 }
3377 }
3378
3379 private final IContentProvider getProvider(Context context, String name) {
3380 IContentProvider existing = getExistingProvider(context, name);
3381 if (existing != null) {
3382 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 }
3384
3385 IActivityManager.ContentProviderHolder holder = null;
3386 try {
3387 holder = ActivityManagerNative.getDefault().getContentProvider(
3388 getApplicationThread(), name);
3389 } catch (RemoteException ex) {
3390 }
3391 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003392 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 return null;
3394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395
3396 IContentProvider prov = installProvider(context, holder.provider,
3397 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003398 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 if (holder.noReleaseNeeded || holder.provider == null) {
3400 // We are not going to release the provider if it is an external
3401 // provider that doesn't care about being released, or if it is
3402 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003403 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 synchronized(mProviderMap) {
3405 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3406 }
3407 }
3408 return prov;
3409 }
3410
3411 public final IContentProvider acquireProvider(Context c, String name) {
3412 IContentProvider provider = getProvider(c, name);
3413 if(provider == null)
3414 return null;
3415 IBinder jBinder = provider.asBinder();
3416 synchronized(mProviderMap) {
3417 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3418 if(prc == null) {
3419 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3420 } else {
3421 prc.count++;
3422 } //end else
3423 } //end synchronized
3424 return provider;
3425 }
3426
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003427 public final IContentProvider acquireExistingProvider(Context c, String name) {
3428 IContentProvider provider = getExistingProvider(c, name);
3429 if(provider == null)
3430 return null;
3431 IBinder jBinder = provider.asBinder();
3432 synchronized(mProviderMap) {
3433 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3434 if(prc == null) {
3435 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3436 } else {
3437 prc.count++;
3438 } //end else
3439 } //end synchronized
3440 return provider;
3441 }
3442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 public final boolean releaseProvider(IContentProvider provider) {
3444 if(provider == null) {
3445 return false;
3446 }
3447 IBinder jBinder = provider.asBinder();
3448 synchronized(mProviderMap) {
3449 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3450 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003451 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 return false;
3453 } else {
3454 prc.count--;
3455 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003456 // Schedule the actual remove asynchronously, since we
3457 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003458 // TODO: it would be nice to post a delayed message, so
3459 // if we come back and need the same provider quickly
3460 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003461 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3462 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 } //end if
3464 } //end else
3465 } //end synchronized
3466 return true;
3467 }
3468
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003469 final void completeRemoveProvider(IContentProvider provider) {
3470 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003471 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003472 synchronized(mProviderMap) {
3473 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3474 if(prc != null && prc.count == 0) {
3475 mProviderRefCountMap.remove(jBinder);
3476 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003477 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003478 }
3479 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003480
3481 if (name != null) {
3482 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003483 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003484 "ActivityManagerNative.removeContentProvider(" + name);
3485 ActivityManagerNative.getDefault().removeContentProvider(
3486 getApplicationThread(), name);
3487 } catch (RemoteException e) {
3488 //do nothing content provider object is dead any way
3489 } //end catch
3490 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003491 }
3492
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003493 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003495 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 }
3497 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003499 String name = null;
3500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003502 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003504 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 IBinder myBinder = pr.mProvider.asBinder();
3506 if (myBinder == providerBinder) {
3507 //find if its published by this process itself
3508 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003509 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003510 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003512 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 "death recipient");
3514 //content provider is in another process
3515 myBinder.unlinkToDeath(pr, 0);
3516 iter.remove();
3517 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003518 if(name == null) {
3519 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 }
3521 } //end if myBinder
3522 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003523
3524 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 }
3526
3527 final void removeDeadProvider(String name, IContentProvider provider) {
3528 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003529 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003531 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003532 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003533 if (removed != null) {
3534 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 }
3537 }
3538 }
3539
3540 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003541 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003543 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003544 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003545 if (removed != null) {
3546 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 }
3549 }
3550
3551 private final IContentProvider installProvider(Context context,
3552 IContentProvider provider, ProviderInfo info, boolean noisy) {
3553 ContentProvider localProvider = null;
3554 if (provider == null) {
3555 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003556 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 + info.name);
3558 }
3559 Context c = null;
3560 ApplicationInfo ai = info.applicationInfo;
3561 if (context.getPackageName().equals(ai.packageName)) {
3562 c = context;
3563 } else if (mInitialApplication != null &&
3564 mInitialApplication.getPackageName().equals(ai.packageName)) {
3565 c = mInitialApplication;
3566 } else {
3567 try {
3568 c = context.createPackageContext(ai.packageName,
3569 Context.CONTEXT_INCLUDE_CODE);
3570 } catch (PackageManager.NameNotFoundException e) {
3571 }
3572 }
3573 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003574 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 ai.packageName +
3576 " while loading content provider " +
3577 info.name);
3578 return null;
3579 }
3580 try {
3581 final java.lang.ClassLoader cl = c.getClassLoader();
3582 localProvider = (ContentProvider)cl.
3583 loadClass(info.name).newInstance();
3584 provider = localProvider.getIContentProvider();
3585 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003586 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 info.name + " from sourceDir " +
3588 info.applicationInfo.sourceDir);
3589 return null;
3590 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003591 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 TAG, "Instantiating local provider " + info.name);
3593 // XXX Need to create the correct context for this provider.
3594 localProvider.attachInfo(c, info);
3595 } catch (java.lang.Exception e) {
3596 if (!mInstrumentation.onException(null, e)) {
3597 throw new RuntimeException(
3598 "Unable to get provider " + info.name
3599 + ": " + e.toString(), e);
3600 }
3601 return null;
3602 }
3603 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003604 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 + info.name);
3606 }
3607
3608 synchronized (mProviderMap) {
3609 // Cache the pointer for the remote provider.
3610 String names[] = PATTERN_SEMICOLON.split(info.authority);
3611 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003612 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 localProvider);
3614 try {
3615 provider.asBinder().linkToDeath(pr, 0);
3616 mProviderMap.put(names[i], pr);
3617 } catch (RemoteException e) {
3618 return null;
3619 }
3620 }
3621 if (localProvider != null) {
3622 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003623 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 }
3625 }
3626
3627 return provider;
3628 }
3629
3630 private final void attach(boolean system) {
3631 sThreadLocal.set(this);
3632 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003634 ViewRoot.addFirstDrawHandler(new Runnable() {
3635 public void run() {
3636 ensureJitEnabled();
3637 }
3638 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3640 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3641 IActivityManager mgr = ActivityManagerNative.getDefault();
3642 try {
3643 mgr.attachApplication(mAppThread);
3644 } catch (RemoteException ex) {
3645 }
3646 } else {
3647 // Don't set application object here -- if the system crashes,
3648 // we can't display an alert, we just want to die die die.
3649 android.ddm.DdmHandleAppName.setAppName("system_process");
3650 try {
3651 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003652 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 context.init(getSystemContext().mPackageInfo, null, this);
3654 Application app = Instrumentation.newApplication(Application.class, context);
3655 mAllApplications.add(app);
3656 mInitialApplication = app;
3657 app.onCreate();
3658 } catch (Exception e) {
3659 throw new RuntimeException(
3660 "Unable to instantiate Application():" + e.toString(), e);
3661 }
3662 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003663
3664 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3665 public void onConfigurationChanged(Configuration newConfig) {
3666 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003667 // We need to apply this change to the resources
3668 // immediately, because upon returning the view
3669 // hierarchy will be informed about it.
3670 if (applyConfigurationToResourcesLocked(newConfig)) {
3671 // This actually changed the resources! Tell
3672 // everyone about it.
3673 if (mPendingConfiguration == null ||
3674 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3675 mPendingConfiguration = newConfig;
3676
3677 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3678 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003679 }
3680 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003681 }
3682 public void onLowMemory() {
3683 }
3684 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 }
3686
3687 private final void detach()
3688 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 sThreadLocal.set(null);
3690 }
3691
3692 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003693 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 ActivityThread thread = new ActivityThread();
3695 thread.attach(true);
3696 return thread;
3697 }
3698
3699 public final void installSystemProviders(List providers) {
3700 if (providers != null) {
3701 installContentProviders(mInitialApplication,
3702 (List<ProviderInfo>)providers);
3703 }
3704 }
3705
3706 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003707 SamplingProfilerIntegration.start();
3708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 Process.setArgV0("<pre-initialized>");
3710
3711 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003712 if (sMainThreadHandler == null) {
3713 sMainThreadHandler = new Handler();
3714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715
3716 ActivityThread thread = new ActivityThread();
3717 thread.attach(false);
3718
Dianne Hackborn287952c2010-09-22 22:34:31 -07003719 if (false) {
3720 Looper.myLooper().setMessageLogging(new
3721 LogPrinter(Log.DEBUG, "ActivityThread"));
3722 }
3723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 Looper.loop();
3725
3726 if (Process.supportsProcesses()) {
3727 throw new RuntimeException("Main thread loop unexpectedly exited");
3728 }
3729
3730 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003731 String name = (thread.mInitialApplication != null)
3732 ? thread.mInitialApplication.getPackageName()
3733 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003734 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 }
3736}