blob: aa207e812d6b862756a4bcd52b2e6b7622f93ffe [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 Hackbornc9421ba2010-03-11 22:23:46 -080064import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.view.Display;
66import android.view.View;
67import android.view.ViewDebug;
68import android.view.ViewManager;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080069import android.view.ViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.Window;
71import android.view.WindowManager;
72import android.view.WindowManagerImpl;
73
74import com.android.internal.os.BinderInternal;
75import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070076import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
78import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
79
80import java.io.File;
81import java.io.FileDescriptor;
82import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070083import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import java.io.PrintWriter;
85import java.lang.ref.WeakReference;
86import java.util.ArrayList;
87import java.util.HashMap;
88import java.util.Iterator;
89import java.util.List;
90import java.util.Locale;
91import java.util.Map;
92import java.util.TimeZone;
93import java.util.regex.Pattern;
94
Bob Leee5408332009-09-04 18:31:17 -070095import dalvik.system.SamplingProfiler;
96
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097final class SuperNotCalledException extends AndroidRuntimeException {
98 public SuperNotCalledException(String msg) {
99 super(msg);
100 }
101}
102
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700103final class RemoteServiceException extends AndroidRuntimeException {
104 public RemoteServiceException(String msg) {
105 super(msg);
106 }
107}
108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109/**
110 * This manages the execution of the main thread in an
111 * application process, scheduling and executing activities,
112 * broadcasts, and other operations on it as the activity
113 * manager requests.
114 *
115 * {@hide}
116 */
117public final class ActivityThread {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700118 static final String TAG = "ActivityThread";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700120 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
121 static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700122 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700123 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700124 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
126 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
127 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
128 private static final int LOG_ON_PAUSE_CALLED = 30021;
129 private static final int LOG_ON_RESUME_CALLED = 30022;
130
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700131 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700132
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700133 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700135 final ApplicationThread mAppThread = new ApplicationThread();
136 final Looper mLooper = Looper.myLooper();
137 final H mH = new H();
138 final HashMap<IBinder, ActivityClientRecord> mActivities
139 = new HashMap<IBinder, ActivityClientRecord>();
140 // List of new activities (via ActivityRecord.nextIdle) that should
141 // be reported when next we idle.
142 ActivityClientRecord mNewActivities = null;
143 // Number of activities that are currently visible on-screen.
144 int mNumVisibleActivities = 0;
145 final HashMap<IBinder, Service> mServices
146 = new HashMap<IBinder, Service>();
147 AppBindData mBoundApplication;
148 Configuration mConfiguration;
149 Configuration mResConfiguration;
150 Application mInitialApplication;
151 final ArrayList<Application> mAllApplications
152 = new ArrayList<Application>();
153 // set of instantiated backup agents, keyed by package name
154 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
155 static final ThreadLocal sThreadLocal = new ThreadLocal();
156 Instrumentation mInstrumentation;
157 String mInstrumentationAppDir = null;
158 String mInstrumentationAppPackage = null;
159 String mInstrumentedAppDir = null;
160 boolean mSystemThread = false;
161 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700163 // These can be accessed by multiple threads; mPackages is the lock.
164 // XXX For now we keep around information about all packages we have
165 // seen, not removing entries from this map.
166 final HashMap<String, WeakReference<LoadedApk>> mPackages
167 = new HashMap<String, WeakReference<LoadedApk>>();
168 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
169 = new HashMap<String, WeakReference<LoadedApk>>();
170 Display mDisplay = null;
171 DisplayMetrics mDisplayMetrics = null;
172 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
173 = new HashMap<ResourcesKey, WeakReference<Resources> >();
174 final ArrayList<ActivityClientRecord> mRelaunchingActivities
175 = new ArrayList<ActivityClientRecord>();
176 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700178 // The lock of mProviderMap protects the following variables.
179 final HashMap<String, ProviderClientRecord> mProviderMap
180 = new HashMap<String, ProviderClientRecord>();
181 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
182 = new HashMap<IBinder, ProviderRefCount>();
183 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
184 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700186 final GcIdler mGcIdler = new GcIdler();
187 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700189 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700191 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 Intent intent;
193 Bundle state;
194 Activity activity;
195 Window window;
196 Activity parent;
197 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700198 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 boolean paused;
200 boolean stopped;
201 boolean hideForNow;
202 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700203 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700204 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
206 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700207 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
209 List<ResultInfo> pendingResults;
210 List<Intent> pendingIntents;
211
212 boolean startsNotResumed;
213 boolean isForward;
214
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700215 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 parent = null;
217 embeddedID = null;
218 paused = false;
219 stopped = false;
220 hideForNow = false;
221 nextIdle = null;
222 }
223
224 public String toString() {
225 ComponentName componentName = intent.getComponent();
226 return "ActivityRecord{"
227 + Integer.toHexString(System.identityHashCode(this))
228 + " token=" + token + " " + (componentName == null
229 ? "no component name" : componentName.toShortString())
230 + "}";
231 }
232 }
233
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700234 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 final String mName;
236 final IContentProvider mProvider;
237 final ContentProvider mLocalProvider;
238
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700239 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 ContentProvider localProvider) {
241 mName = name;
242 mProvider = provider;
243 mLocalProvider = localProvider;
244 }
245
246 public void binderDied() {
247 removeDeadProvider(mName, mProvider);
248 }
249 }
250
251 private static final class NewIntentData {
252 List<Intent> intents;
253 IBinder token;
254 public String toString() {
255 return "NewIntentData{intents=" + intents + " token=" + token + "}";
256 }
257 }
258
259 private static final class ReceiverData {
260 Intent intent;
261 ActivityInfo info;
262 int resultCode;
263 String resultData;
264 Bundle resultExtras;
265 boolean sync;
266 boolean resultAbort;
267 public String toString() {
268 return "ReceiverData{intent=" + intent + " packageName=" +
269 info.packageName + " resultCode=" + resultCode
270 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
271 }
272 }
273
Christopher Tate181fafa2009-05-14 11:12:14 -0700274 private static final class CreateBackupAgentData {
275 ApplicationInfo appInfo;
276 int backupMode;
277 public String toString() {
278 return "CreateBackupAgentData{appInfo=" + appInfo
279 + " backupAgent=" + appInfo.backupAgentName
280 + " mode=" + backupMode + "}";
281 }
282 }
Bob Leee5408332009-09-04 18:31:17 -0700283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 private static final class CreateServiceData {
285 IBinder token;
286 ServiceInfo info;
287 Intent intent;
288 public String toString() {
289 return "CreateServiceData{token=" + token + " className="
290 + info.name + " packageName=" + info.packageName
291 + " intent=" + intent + "}";
292 }
293 }
294
295 private static final class BindServiceData {
296 IBinder token;
297 Intent intent;
298 boolean rebind;
299 public String toString() {
300 return "BindServiceData{token=" + token + " intent=" + intent + "}";
301 }
302 }
303
304 private static final class ServiceArgsData {
305 IBinder token;
306 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700307 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 Intent args;
309 public String toString() {
310 return "ServiceArgsData{token=" + token + " startId=" + startId
311 + " args=" + args + "}";
312 }
313 }
314
315 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700316 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 String processName;
318 ApplicationInfo appInfo;
319 List<ProviderInfo> providers;
320 ComponentName instrumentationName;
321 String profileFile;
322 Bundle instrumentationArgs;
323 IInstrumentationWatcher instrumentationWatcher;
324 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700325 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 Configuration config;
327 boolean handlingProfiling;
328 public String toString() {
329 return "AppBindData{appInfo=" + appInfo + "}";
330 }
331 }
332
333 private static final class DumpServiceInfo {
334 FileDescriptor fd;
335 IBinder service;
336 String[] args;
337 boolean dumped;
338 }
339
340 private static final class ResultData {
341 IBinder token;
342 List<ResultInfo> results;
343 public String toString() {
344 return "ResultData{token=" + token + " results" + results + "}";
345 }
346 }
347
348 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800349 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 String what;
351 String who;
352 }
353
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700354 private static final class ProfilerControlData {
355 String path;
356 ParcelFileDescriptor fd;
357 }
358
Andy McFadden824c5102010-07-09 16:26:57 -0700359 private static final class DumpHeapData {
360 String path;
361 ParcelFileDescriptor fd;
362 }
363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 private final class ApplicationThread extends ApplicationThreadNative {
365 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
366 private static final String ONE_COUNT_COLUMN = "%17s %8d";
367 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Nori90a367262010-04-12 12:49:09 -0700368 private static final String DB_INFO_FORMAT = " %4d %6d %8d %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 // Formatting for checkin service - update version if row format changes
371 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 public final void schedulePauseActivity(IBinder token, boolean finished,
374 boolean userLeaving, int configChanges) {
375 queueOrSendMessage(
376 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
377 token,
378 (userLeaving ? 1 : 0),
379 configChanges);
380 }
381
382 public final void scheduleStopActivity(IBinder token, boolean showWindow,
383 int configChanges) {
384 queueOrSendMessage(
385 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
386 token, 0, configChanges);
387 }
388
389 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
390 queueOrSendMessage(
391 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
392 token);
393 }
394
395 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
396 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
397 }
398
399 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
400 ResultData res = new ResultData();
401 res.token = token;
402 res.results = results;
403 queueOrSendMessage(H.SEND_RESULT, res);
404 }
405
406 // we use token to identify this activity without having to send the
407 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700408 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
410 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700411 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412
413 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700414 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 r.intent = intent;
416 r.activityInfo = info;
417 r.state = state;
418
419 r.pendingResults = pendingResults;
420 r.pendingIntents = pendingNewIntents;
421
422 r.startsNotResumed = notResumed;
423 r.isForward = isForward;
424
425 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
426 }
427
428 public final void scheduleRelaunchActivity(IBinder token,
429 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800430 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700431 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432
433 r.token = token;
434 r.pendingResults = pendingResults;
435 r.pendingIntents = pendingNewIntents;
436 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800437 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800439 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 mRelaunchingActivities.add(r);
441 }
Bob Leee5408332009-09-04 18:31:17 -0700442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
444 }
445
446 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
447 NewIntentData data = new NewIntentData();
448 data.intents = intents;
449 data.token = token;
450
451 queueOrSendMessage(H.NEW_INTENT, data);
452 }
453
454 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
455 int configChanges) {
456 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
457 configChanges);
458 }
459
460 public final void scheduleReceiver(Intent intent, ActivityInfo info,
461 int resultCode, String data, Bundle extras, boolean sync) {
462 ReceiverData r = new ReceiverData();
463
464 r.intent = intent;
465 r.info = info;
466 r.resultCode = resultCode;
467 r.resultData = data;
468 r.resultExtras = extras;
469 r.sync = sync;
470
471 queueOrSendMessage(H.RECEIVER, r);
472 }
473
Christopher Tate181fafa2009-05-14 11:12:14 -0700474 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
475 CreateBackupAgentData d = new CreateBackupAgentData();
476 d.appInfo = app;
477 d.backupMode = backupMode;
478
479 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
480 }
481
482 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
483 CreateBackupAgentData d = new CreateBackupAgentData();
484 d.appInfo = app;
485
486 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
487 }
488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 public final void scheduleCreateService(IBinder token,
490 ServiceInfo info) {
491 CreateServiceData s = new CreateServiceData();
492 s.token = token;
493 s.info = info;
494
495 queueOrSendMessage(H.CREATE_SERVICE, s);
496 }
497
498 public final void scheduleBindService(IBinder token, Intent intent,
499 boolean rebind) {
500 BindServiceData s = new BindServiceData();
501 s.token = token;
502 s.intent = intent;
503 s.rebind = rebind;
504
505 queueOrSendMessage(H.BIND_SERVICE, s);
506 }
507
508 public final void scheduleUnbindService(IBinder token, Intent intent) {
509 BindServiceData s = new BindServiceData();
510 s.token = token;
511 s.intent = intent;
512
513 queueOrSendMessage(H.UNBIND_SERVICE, s);
514 }
515
516 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700517 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 ServiceArgsData s = new ServiceArgsData();
519 s.token = token;
520 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700521 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 s.args = args;
523
524 queueOrSendMessage(H.SERVICE_ARGS, s);
525 }
526
527 public final void scheduleStopService(IBinder token) {
528 queueOrSendMessage(H.STOP_SERVICE, token);
529 }
530
531 public final void bindApplication(String processName,
532 ApplicationInfo appInfo, List<ProviderInfo> providers,
533 ComponentName instrumentationName, String profileFile,
534 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700535 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537
538 if (services != null) {
539 // Setup the service cache in the ServiceManager
540 ServiceManager.initServiceCache(services);
541 }
542
543 AppBindData data = new AppBindData();
544 data.processName = processName;
545 data.appInfo = appInfo;
546 data.providers = providers;
547 data.instrumentationName = instrumentationName;
548 data.profileFile = profileFile;
549 data.instrumentationArgs = instrumentationArgs;
550 data.instrumentationWatcher = instrumentationWatcher;
551 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700552 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 data.config = config;
554 queueOrSendMessage(H.BIND_APPLICATION, data);
555 }
556
557 public final void scheduleExit() {
558 queueOrSendMessage(H.EXIT_APPLICATION, null);
559 }
560
Christopher Tate5e1ab332009-09-01 20:32:49 -0700561 public final void scheduleSuicide() {
562 queueOrSendMessage(H.SUICIDE, null);
563 }
564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 public void requestThumbnail(IBinder token) {
566 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
567 }
568
569 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800570 synchronized (mPackages) {
571 if (mPendingConfiguration == null ||
572 mPendingConfiguration.isOtherSeqNewer(config)) {
573 mPendingConfiguration = config;
574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
576 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
577 }
578
579 public void updateTimeZone() {
580 TimeZone.setDefault(null);
581 }
582
583 public void processInBackground() {
584 mH.removeMessages(H.GC_WHEN_IDLE);
585 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
586 }
587
588 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
589 DumpServiceInfo data = new DumpServiceInfo();
590 data.fd = fd;
591 data.service = servicetoken;
592 data.args = args;
593 data.dumped = false;
594 queueOrSendMessage(H.DUMP_SERVICE, data);
595 synchronized (data) {
596 while (!data.dumped) {
597 try {
598 data.wait();
599 } catch (InterruptedException e) {
600 // no need to do anything here, we will keep waiting until
601 // dumped is set
602 }
603 }
604 }
605 }
606
607 // This function exists to make sure all receiver dispatching is
608 // correctly ordered, since these are one-way calls and the binder driver
609 // applies transaction ordering per object for such calls.
610 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700611 int resultCode, String dataStr, Bundle extras, boolean ordered,
612 boolean sticky) throws RemoteException {
613 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 }
Bob Leee5408332009-09-04 18:31:17 -0700615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 public void scheduleLowMemory() {
617 queueOrSendMessage(H.LOW_MEMORY, null);
618 }
619
620 public void scheduleActivityConfigurationChanged(IBinder token) {
621 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
622 }
623
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700624 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
625 ProfilerControlData pcd = new ProfilerControlData();
626 pcd.path = path;
627 pcd.fd = fd;
628 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800629 }
630
Andy McFadden824c5102010-07-09 16:26:57 -0700631 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
632 DumpHeapData dhd = new DumpHeapData();
633 dhd.path = path;
634 dhd.fd = fd;
635 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
636 }
637
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700638 public void setSchedulingGroup(int group) {
639 // Note: do this immediately, since going into the foreground
640 // should happen regardless of what pending work we have to do
641 // and the activity manager will wait for us to report back that
642 // we are done before sending us to the background.
643 try {
644 Process.setProcessGroup(Process.myPid(), group);
645 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800646 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700647 }
648 }
Bob Leee5408332009-09-04 18:31:17 -0700649
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700650 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
651 Debug.getMemoryInfo(outInfo);
652 }
Bob Leee5408332009-09-04 18:31:17 -0700653
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700654 public void dispatchPackageBroadcast(int cmd, String[] packages) {
655 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
656 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700657
658 public void scheduleCrash(String msg) {
659 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
660 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 @Override
663 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
664 long nativeMax = Debug.getNativeHeapSize() / 1024;
665 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
666 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
667
668 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
669 Debug.getMemoryInfo(memInfo);
670
671 final int nativeShared = memInfo.nativeSharedDirty;
672 final int dalvikShared = memInfo.dalvikSharedDirty;
673 final int otherShared = memInfo.otherSharedDirty;
674
675 final int nativePrivate = memInfo.nativePrivateDirty;
676 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
677 final int otherPrivate = memInfo.otherPrivateDirty;
678
679 Runtime runtime = Runtime.getRuntime();
680
681 long dalvikMax = runtime.totalMemory() / 1024;
682 long dalvikFree = runtime.freeMemory() / 1024;
683 long dalvikAllocated = dalvikMax - dalvikFree;
684 long viewInstanceCount = ViewDebug.getViewInstanceCount();
685 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Dianne Hackborn21556372010-02-04 16:34:40 -0800686 long appContextInstanceCount = ContextImpl.getInstanceCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 long activityInstanceCount = Activity.getInstanceCount();
688 int globalAssetCount = AssetManager.getGlobalAssetCount();
689 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
690 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
691 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
692 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
693 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
694 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800695 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 // Check to see if we were called by checkin server. If so, print terse format.
698 boolean doCheckinFormat = false;
699 if (args != null) {
700 for (String arg : args) {
701 if ("-c".equals(arg)) doCheckinFormat = true;
702 }
703 }
Bob Leee5408332009-09-04 18:31:17 -0700704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 // For checkin, we print one long comma-separated list of values
706 if (doCheckinFormat) {
707 // NOTE: if you change anything significant below, also consider changing
708 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700709 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 // Header
713 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
714 pw.print(Process.myPid()); pw.print(',');
715 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 // Heap info - max
718 pw.print(nativeMax); pw.print(',');
719 pw.print(dalvikMax); pw.print(',');
720 pw.print("N/A,");
721 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 // Heap info - allocated
724 pw.print(nativeAllocated); pw.print(',');
725 pw.print(dalvikAllocated); pw.print(',');
726 pw.print("N/A,");
727 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 // Heap info - free
730 pw.print(nativeFree); pw.print(',');
731 pw.print(dalvikFree); pw.print(',');
732 pw.print("N/A,");
733 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 // Heap info - proportional set size
736 pw.print(memInfo.nativePss); pw.print(',');
737 pw.print(memInfo.dalvikPss); pw.print(',');
738 pw.print(memInfo.otherPss); pw.print(',');
739 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700742 pw.print(nativeShared); pw.print(',');
743 pw.print(dalvikShared); pw.print(',');
744 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700748 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 pw.print(dalvikPrivate); pw.print(',');
750 pw.print(otherPrivate); pw.print(',');
751 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 // Object counts
754 pw.print(viewInstanceCount); pw.print(',');
755 pw.print(viewRootInstanceCount); pw.print(',');
756 pw.print(appContextInstanceCount); pw.print(',');
757 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 pw.print(globalAssetCount); pw.print(',');
760 pw.print(globalAssetManagerCount); pw.print(',');
761 pw.print(binderLocalObjectCount); pw.print(',');
762 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 pw.print(binderDeathObjectCount); pw.print(',');
765 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 // SQL
768 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800769 pw.print(stats.memoryUsed / 1024); pw.print(',');
770 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
771 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
772 for (int i = 0; i < stats.dbStats.size(); i++) {
773 DbStats dbStats = stats.dbStats.get(i);
774 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700775 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800776 pw.print(',');
777 }
Bob Leee5408332009-09-04 18:31:17 -0700778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 return;
780 }
Bob Leee5408332009-09-04 18:31:17 -0700781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 // otherwise, show human-readable format
783 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
784 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
785 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
786 nativeAllocated + dalvikAllocated);
787 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
788 nativeFree + dalvikFree);
789
790 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
791 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
792
793 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
794 nativeShared + dalvikShared + otherShared);
795 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
796 nativePrivate + dalvikPrivate + otherPrivate);
797
798 pw.println(" ");
799 pw.println(" Objects");
800 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
801 viewRootInstanceCount);
802
803 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
804 "Activities:", activityInstanceCount);
805
806 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
807 "AssetManagers:", globalAssetManagerCount);
808
809 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
810 "Proxy Binders:", binderProxyObjectCount);
811 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
812
813 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 // SQLite mem info
816 pw.println(" ");
817 pw.println(" SQL");
Vasu Noric3849202010-03-09 10:47:25 -0800818 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "memoryUsed:",
819 stats.memoryUsed / 1024);
820 printRow(pw, TWO_COUNT_COLUMNS, "pageCacheOverflo:", stats.pageCacheOverflo / 1024,
821 "largestMemAlloc:", stats.largestMemAlloc / 1024);
822 pw.println(" ");
823 int N = stats.dbStats.size();
824 if (N > 0) {
825 pw.println(" DATABASES");
Vasu Nori90a367262010-04-12 12:49:09 -0700826 printRow(pw, " %4s %6s %8s %14s %s", "pgsz", "dbsz", "lkaside", "cache",
827 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800828 for (int i = 0; i < N; i++) {
829 DbStats dbStats = stats.dbStats.get(i);
830 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700831 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800832 }
833 }
Bob Leee5408332009-09-04 18:31:17 -0700834
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700835 // Asset details.
836 String assetAlloc = AssetManager.getAssetAllocations();
837 if (assetAlloc != null) {
838 pw.println(" ");
839 pw.println(" Asset Allocations");
840 pw.print(assetAlloc);
841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
843
844 private void printRow(PrintWriter pw, String format, Object...objs) {
845 pw.println(String.format(format, objs));
846 }
847 }
848
849 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -0700850 private H() {
851 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
852 }
853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 public static final int LAUNCH_ACTIVITY = 100;
855 public static final int PAUSE_ACTIVITY = 101;
856 public static final int PAUSE_ACTIVITY_FINISHING= 102;
857 public static final int STOP_ACTIVITY_SHOW = 103;
858 public static final int STOP_ACTIVITY_HIDE = 104;
859 public static final int SHOW_WINDOW = 105;
860 public static final int HIDE_WINDOW = 106;
861 public static final int RESUME_ACTIVITY = 107;
862 public static final int SEND_RESULT = 108;
863 public static final int DESTROY_ACTIVITY = 109;
864 public static final int BIND_APPLICATION = 110;
865 public static final int EXIT_APPLICATION = 111;
866 public static final int NEW_INTENT = 112;
867 public static final int RECEIVER = 113;
868 public static final int CREATE_SERVICE = 114;
869 public static final int SERVICE_ARGS = 115;
870 public static final int STOP_SERVICE = 116;
871 public static final int REQUEST_THUMBNAIL = 117;
872 public static final int CONFIGURATION_CHANGED = 118;
873 public static final int CLEAN_UP_CONTEXT = 119;
874 public static final int GC_WHEN_IDLE = 120;
875 public static final int BIND_SERVICE = 121;
876 public static final int UNBIND_SERVICE = 122;
877 public static final int DUMP_SERVICE = 123;
878 public static final int LOW_MEMORY = 124;
879 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
880 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800881 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700882 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700883 public static final int DESTROY_BACKUP_AGENT = 129;
884 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700885 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800886 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700887 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700888 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700889 public static final int DUMP_HEAP = 135;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 String codeToString(int code) {
891 if (localLOGV) {
892 switch (code) {
893 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
894 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
895 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
896 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
897 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
898 case SHOW_WINDOW: return "SHOW_WINDOW";
899 case HIDE_WINDOW: return "HIDE_WINDOW";
900 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
901 case SEND_RESULT: return "SEND_RESULT";
902 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
903 case BIND_APPLICATION: return "BIND_APPLICATION";
904 case EXIT_APPLICATION: return "EXIT_APPLICATION";
905 case NEW_INTENT: return "NEW_INTENT";
906 case RECEIVER: return "RECEIVER";
907 case CREATE_SERVICE: return "CREATE_SERVICE";
908 case SERVICE_ARGS: return "SERVICE_ARGS";
909 case STOP_SERVICE: return "STOP_SERVICE";
910 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
911 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
912 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
913 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
914 case BIND_SERVICE: return "BIND_SERVICE";
915 case UNBIND_SERVICE: return "UNBIND_SERVICE";
916 case DUMP_SERVICE: return "DUMP_SERVICE";
917 case LOW_MEMORY: return "LOW_MEMORY";
918 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
919 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800920 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700921 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
922 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700923 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700924 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800925 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700926 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700927 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -0700928 case DUMP_HEAP: return "DUMP_HEAP";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
930 }
931 return "(unknown)";
932 }
933 public void handleMessage(Message msg) {
934 switch (msg.what) {
935 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700936 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937
938 r.packageInfo = getPackageInfoNoCheck(
939 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700940 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 } break;
942 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700943 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 handleRelaunchActivity(r, msg.arg1);
945 } break;
946 case PAUSE_ACTIVITY:
947 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700948 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 break;
950 case PAUSE_ACTIVITY_FINISHING:
951 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
952 break;
953 case STOP_ACTIVITY_SHOW:
954 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
955 break;
956 case STOP_ACTIVITY_HIDE:
957 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
958 break;
959 case SHOW_WINDOW:
960 handleWindowVisibility((IBinder)msg.obj, true);
961 break;
962 case HIDE_WINDOW:
963 handleWindowVisibility((IBinder)msg.obj, false);
964 break;
965 case RESUME_ACTIVITY:
966 handleResumeActivity((IBinder)msg.obj, true,
967 msg.arg1 != 0);
968 break;
969 case SEND_RESULT:
970 handleSendResult((ResultData)msg.obj);
971 break;
972 case DESTROY_ACTIVITY:
973 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
974 msg.arg2, false);
975 break;
976 case BIND_APPLICATION:
977 AppBindData data = (AppBindData)msg.obj;
978 handleBindApplication(data);
979 break;
980 case EXIT_APPLICATION:
981 if (mInitialApplication != null) {
982 mInitialApplication.onTerminate();
983 }
984 Looper.myLooper().quit();
985 break;
986 case NEW_INTENT:
987 handleNewIntent((NewIntentData)msg.obj);
988 break;
989 case RECEIVER:
990 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700991 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 break;
993 case CREATE_SERVICE:
994 handleCreateService((CreateServiceData)msg.obj);
995 break;
996 case BIND_SERVICE:
997 handleBindService((BindServiceData)msg.obj);
998 break;
999 case UNBIND_SERVICE:
1000 handleUnbindService((BindServiceData)msg.obj);
1001 break;
1002 case SERVICE_ARGS:
1003 handleServiceArgs((ServiceArgsData)msg.obj);
1004 break;
1005 case STOP_SERVICE:
1006 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001007 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 break;
1009 case REQUEST_THUMBNAIL:
1010 handleRequestThumbnail((IBinder)msg.obj);
1011 break;
1012 case CONFIGURATION_CHANGED:
1013 handleConfigurationChanged((Configuration)msg.obj);
1014 break;
1015 case CLEAN_UP_CONTEXT:
1016 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1017 cci.context.performFinalCleanup(cci.who, cci.what);
1018 break;
1019 case GC_WHEN_IDLE:
1020 scheduleGcIdler();
1021 break;
1022 case DUMP_SERVICE:
1023 handleDumpService((DumpServiceInfo)msg.obj);
1024 break;
1025 case LOW_MEMORY:
1026 handleLowMemory();
1027 break;
1028 case ACTIVITY_CONFIGURATION_CHANGED:
1029 handleActivityConfigurationChanged((IBinder)msg.obj);
1030 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001031 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001032 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001033 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001034 case CREATE_BACKUP_AGENT:
1035 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1036 break;
1037 case DESTROY_BACKUP_AGENT:
1038 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1039 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001040 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001041 Process.killProcess(Process.myPid());
1042 break;
1043 case REMOVE_PROVIDER:
1044 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001045 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001046 case ENABLE_JIT:
1047 ensureJitEnabled();
1048 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001049 case DISPATCH_PACKAGE_BROADCAST:
1050 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1051 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001052 case SCHEDULE_CRASH:
1053 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001054 case DUMP_HEAP:
1055 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1056 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058 }
Bob Leee5408332009-09-04 18:31:17 -07001059
1060 void maybeSnapshot() {
1061 if (mBoundApplication != null) {
Sen Hubde75702010-05-28 01:54:03 -07001062 // convert the *private* ActivityThread.PackageInfo to *public* known
1063 // android.content.pm.PackageInfo
1064 String packageName = mBoundApplication.info.mPackageName;
1065 android.content.pm.PackageInfo packageInfo = null;
1066 try {
1067 Context context = getSystemContext();
1068 if(context == null) {
1069 Log.e(TAG, "cannot get a valid context");
1070 return;
1071 }
1072 PackageManager pm = context.getPackageManager();
1073 if(pm == null) {
1074 Log.e(TAG, "cannot get a valid PackageManager");
1075 return;
1076 }
1077 packageInfo = pm.getPackageInfo(
1078 packageName, PackageManager.GET_ACTIVITIES);
1079 } catch (NameNotFoundException e) {
1080 Log.e(TAG, "cannot get package info for " + packageName, e);
1081 }
1082 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001083 }
1084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
1086
1087 private final class Idler implements MessageQueue.IdleHandler {
1088 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001089 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 if (a != null) {
1091 mNewActivities = null;
1092 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001093 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001095 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 TAG, "Reporting idle of " + a +
1097 " finished=" +
1098 (a.activity != null ? a.activity.mFinished : false));
1099 if (a.activity != null && !a.activity.mFinished) {
1100 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001101 am.activityIdle(a.token, a.createdConfig);
1102 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 } catch (RemoteException ex) {
1104 }
1105 }
1106 prev = a;
1107 a = a.nextIdle;
1108 prev.nextIdle = null;
1109 } while (a != null);
1110 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001111 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 return false;
1113 }
1114 }
1115
1116 final class GcIdler implements MessageQueue.IdleHandler {
1117 public final boolean queueIdle() {
1118 doGcIfNeeded();
1119 return false;
1120 }
1121 }
1122
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001123 private final static class ResourcesKey {
1124 final private String mResDir;
1125 final private float mScale;
1126 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001127
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001128 ResourcesKey(String resDir, float scale) {
1129 mResDir = resDir;
1130 mScale = scale;
1131 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1132 }
Bob Leee5408332009-09-04 18:31:17 -07001133
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001134 @Override
1135 public int hashCode() {
1136 return mHash;
1137 }
1138
1139 @Override
1140 public boolean equals(Object obj) {
1141 if (!(obj instanceof ResourcesKey)) {
1142 return false;
1143 }
1144 ResourcesKey peer = (ResourcesKey) obj;
1145 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1146 }
1147 }
1148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001149 public static final ActivityThread currentActivityThread() {
1150 return (ActivityThread)sThreadLocal.get();
1151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001153 public static final String currentPackageName() {
1154 ActivityThread am = currentActivityThread();
1155 return (am != null && am.mBoundApplication != null)
1156 ? am.mBoundApplication.processName : null;
1157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001159 public static final Application currentApplication() {
1160 ActivityThread am = currentActivityThread();
1161 return am != null ? am.mInitialApplication : null;
1162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001164 public static IPackageManager getPackageManager() {
1165 if (sPackageManager != null) {
1166 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1167 return sPackageManager;
1168 }
1169 IBinder b = ServiceManager.getService("package");
1170 //Slog.v("PackageManager", "default service binder = " + b);
1171 sPackageManager = IPackageManager.Stub.asInterface(b);
1172 //Slog.v("PackageManager", "default service = " + sPackageManager);
1173 return sPackageManager;
1174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001176 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1177 if (mDisplayMetrics != null && !forceUpdate) {
1178 return mDisplayMetrics;
1179 }
1180 if (mDisplay == null) {
1181 WindowManager wm = WindowManagerImpl.getDefault();
1182 mDisplay = wm.getDefaultDisplay();
1183 }
1184 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1185 mDisplay.getMetrics(metrics);
1186 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1187 // + metrics.heightPixels + " den=" + metrics.density
1188 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1189 return metrics;
1190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001192 /**
1193 * Creates the top level Resources for applications with the given compatibility info.
1194 *
1195 * @param resDir the resource directory.
1196 * @param compInfo the compability info. It will use the default compatibility info when it's
1197 * null.
1198 */
1199 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1200 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1201 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001203 // Resources is app scale dependent.
1204 if (false) {
1205 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1206 + compInfo.applicationScale);
1207 }
1208 WeakReference<Resources> wr = mActiveResources.get(key);
1209 r = wr != null ? wr.get() : null;
1210 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1211 if (r != null && r.getAssets().isUpToDate()) {
1212 if (false) {
1213 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1214 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1215 }
1216 return r;
1217 }
1218 }
1219
1220 //if (r != null) {
1221 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1222 // + r + " " + resDir);
1223 //}
1224
1225 AssetManager assets = new AssetManager();
1226 if (assets.addAssetPath(resDir) == 0) {
1227 return null;
1228 }
1229
1230 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1231 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1232 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1233 if (false) {
1234 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1235 + r.getConfiguration() + " appScale="
1236 + r.getCompatibilityInfo().applicationScale);
1237 }
1238
1239 synchronized (mPackages) {
1240 WeakReference<Resources> wr = mActiveResources.get(key);
1241 Resources existing = wr != null ? wr.get() : null;
1242 if (existing != null && existing.getAssets().isUpToDate()) {
1243 // Someone else already created the resources while we were
1244 // unlocked; go ahead and use theirs.
1245 r.getAssets().close();
1246 return existing;
1247 }
1248
1249 // XXX need to remove entries when weak references go away
1250 mActiveResources.put(key, new WeakReference<Resources>(r));
1251 return r;
1252 }
1253 }
1254
1255 /**
1256 * Creates the top level resources for the given package.
1257 */
1258 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1259 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1260 }
1261
1262 final Handler getHandler() {
1263 return mH;
1264 }
1265
1266 public final LoadedApk getPackageInfo(String packageName, int flags) {
1267 synchronized (mPackages) {
1268 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1270 ref = mPackages.get(packageName);
1271 } else {
1272 ref = mResourcePackages.get(packageName);
1273 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001274 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001275 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001276 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1277 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 if (packageInfo != null && (packageInfo.mResources == null
1279 || packageInfo.mResources.getAssets().isUpToDate())) {
1280 if (packageInfo.isSecurityViolation()
1281 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1282 throw new SecurityException(
1283 "Requesting code from " + packageName
1284 + " to be run in process "
1285 + mBoundApplication.processName
1286 + "/" + mBoundApplication.appInfo.uid);
1287 }
1288 return packageInfo;
1289 }
1290 }
1291
1292 ApplicationInfo ai = null;
1293 try {
1294 ai = getPackageManager().getApplicationInfo(packageName,
1295 PackageManager.GET_SHARED_LIBRARY_FILES);
1296 } catch (RemoteException e) {
1297 }
1298
1299 if (ai != null) {
1300 return getPackageInfo(ai, flags);
1301 }
1302
1303 return null;
1304 }
1305
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001306 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1308 boolean securityViolation = includeCode && ai.uid != 0
1309 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1310 ? ai.uid != mBoundApplication.appInfo.uid : true);
1311 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1312 |Context.CONTEXT_IGNORE_SECURITY))
1313 == Context.CONTEXT_INCLUDE_CODE) {
1314 if (securityViolation) {
1315 String msg = "Requesting code from " + ai.packageName
1316 + " (with uid " + ai.uid + ")";
1317 if (mBoundApplication != null) {
1318 msg = msg + " to be run in process "
1319 + mBoundApplication.processName + " (with uid "
1320 + mBoundApplication.appInfo.uid + ")";
1321 }
1322 throw new SecurityException(msg);
1323 }
1324 }
1325 return getPackageInfo(ai, null, securityViolation, includeCode);
1326 }
1327
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001328 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 return getPackageInfo(ai, null, false, true);
1330 }
1331
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001332 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1334 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001335 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 if (includeCode) {
1337 ref = mPackages.get(aInfo.packageName);
1338 } else {
1339 ref = mResourcePackages.get(aInfo.packageName);
1340 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001341 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 if (packageInfo == null || (packageInfo.mResources != null
1343 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001344 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 : "Loading resource-only package ") + aInfo.packageName
1346 + " (in " + (mBoundApplication != null
1347 ? mBoundApplication.processName : null)
1348 + ")");
1349 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001350 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 securityViolation, includeCode &&
1352 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1353 if (includeCode) {
1354 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001355 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 } else {
1357 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001358 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 }
1360 }
1361 return packageInfo;
1362 }
1363 }
1364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 ActivityThread() {
1366 }
1367
1368 public ApplicationThread getApplicationThread()
1369 {
1370 return mAppThread;
1371 }
1372
1373 public Instrumentation getInstrumentation()
1374 {
1375 return mInstrumentation;
1376 }
1377
1378 public Configuration getConfiguration() {
1379 return mConfiguration;
1380 }
1381
1382 public boolean isProfiling() {
1383 return mBoundApplication != null && mBoundApplication.profileFile != null;
1384 }
1385
1386 public String getProfileFilePath() {
1387 return mBoundApplication.profileFile;
1388 }
1389
1390 public Looper getLooper() {
1391 return mLooper;
1392 }
1393
1394 public Application getApplication() {
1395 return mInitialApplication;
1396 }
Bob Leee5408332009-09-04 18:31:17 -07001397
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001398 public String getProcessName() {
1399 return mBoundApplication.processName;
1400 }
Bob Leee5408332009-09-04 18:31:17 -07001401
Dianne Hackborn21556372010-02-04 16:34:40 -08001402 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 synchronized (this) {
1404 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001405 ContextImpl context =
1406 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001407 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 context.init(info, null, this);
1409 context.getResources().updateConfiguration(
1410 getConfiguration(), getDisplayMetricsLocked(false));
1411 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001412 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 // + ": " + context.getResources().getConfiguration());
1414 }
1415 }
1416 return mSystemContext;
1417 }
1418
Mike Cleron432b7132009-09-24 15:28:29 -07001419 public void installSystemApplicationInfo(ApplicationInfo info) {
1420 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001421 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001422 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001423 }
1424 }
1425
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001426 void ensureJitEnabled() {
1427 if (!mJitEnabled) {
1428 mJitEnabled = true;
1429 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1430 }
1431 }
1432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 void scheduleGcIdler() {
1434 if (!mGcIdlerScheduled) {
1435 mGcIdlerScheduled = true;
1436 Looper.myQueue().addIdleHandler(mGcIdler);
1437 }
1438 mH.removeMessages(H.GC_WHEN_IDLE);
1439 }
1440
1441 void unscheduleGcIdler() {
1442 if (mGcIdlerScheduled) {
1443 mGcIdlerScheduled = false;
1444 Looper.myQueue().removeIdleHandler(mGcIdler);
1445 }
1446 mH.removeMessages(H.GC_WHEN_IDLE);
1447 }
1448
1449 void doGcIfNeeded() {
1450 mGcIdlerScheduled = false;
1451 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001452 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 // + "m now=" + now);
1454 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001455 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 BinderInternal.forceGc("bg");
1457 }
1458 }
1459
1460 public final ActivityInfo resolveActivityInfo(Intent intent) {
1461 ActivityInfo aInfo = intent.resolveActivityInfo(
1462 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1463 if (aInfo == null) {
1464 // Throw an exception.
1465 Instrumentation.checkStartActivityResult(
1466 IActivityManager.START_CLASS_NOT_FOUND, intent);
1467 }
1468 return aInfo;
1469 }
Bob Leee5408332009-09-04 18:31:17 -07001470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001473 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001474 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001476 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 r.intent = intent;
1478 r.state = state;
1479 r.parent = parent;
1480 r.embeddedID = id;
1481 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001482 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 if (localLOGV) {
1484 ComponentName compname = intent.getComponent();
1485 String name;
1486 if (compname != null) {
1487 name = compname.toShortString();
1488 } else {
1489 name = "(Intent " + intent + ").getComponent() returned null";
1490 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001491 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 + ", comp=" + name
1493 + ", token=" + token);
1494 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001495 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497
1498 public final Activity getActivity(IBinder token) {
1499 return mActivities.get(token).activity;
1500 }
1501
1502 public final void sendActivityResult(
1503 IBinder token, String id, int requestCode,
1504 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001505 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001506 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1508 list.add(new ResultInfo(id, requestCode, resultCode, data));
1509 mAppThread.scheduleSendResult(token, list);
1510 }
1511
1512 // if the thread hasn't started yet, we don't have the handler, so just
1513 // save the messages until we're ready.
1514 private final void queueOrSendMessage(int what, Object obj) {
1515 queueOrSendMessage(what, obj, 0, 0);
1516 }
1517
1518 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1519 queueOrSendMessage(what, obj, arg1, 0);
1520 }
1521
1522 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1523 synchronized (this) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001524 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1526 + ": " + arg1 + " / " + obj);
1527 Message msg = Message.obtain();
1528 msg.what = what;
1529 msg.obj = obj;
1530 msg.arg1 = arg1;
1531 msg.arg2 = arg2;
1532 mH.sendMessage(msg);
1533 }
1534 }
1535
Dianne Hackborn21556372010-02-04 16:34:40 -08001536 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 String what) {
1538 ContextCleanupInfo cci = new ContextCleanupInfo();
1539 cci.context = context;
1540 cci.who = who;
1541 cci.what = what;
1542 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1543 }
1544
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001545 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1547
1548 ActivityInfo aInfo = r.activityInfo;
1549 if (r.packageInfo == null) {
1550 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1551 Context.CONTEXT_INCLUDE_CODE);
1552 }
Bob Leee5408332009-09-04 18:31:17 -07001553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 ComponentName component = r.intent.getComponent();
1555 if (component == null) {
1556 component = r.intent.resolveActivity(
1557 mInitialApplication.getPackageManager());
1558 r.intent.setComponent(component);
1559 }
1560
1561 if (r.activityInfo.targetActivity != null) {
1562 component = new ComponentName(r.activityInfo.packageName,
1563 r.activityInfo.targetActivity);
1564 }
1565
1566 Activity activity = null;
1567 try {
1568 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1569 activity = mInstrumentation.newActivity(
1570 cl, component.getClassName(), r.intent);
1571 r.intent.setExtrasClassLoader(cl);
1572 if (r.state != null) {
1573 r.state.setClassLoader(cl);
1574 }
1575 } catch (Exception e) {
1576 if (!mInstrumentation.onException(activity, e)) {
1577 throw new RuntimeException(
1578 "Unable to instantiate activity " + component
1579 + ": " + e.toString(), e);
1580 }
1581 }
1582
1583 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001584 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001585
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001586 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1587 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 TAG, r + ": app=" + app
1589 + ", appName=" + app.getPackageName()
1590 + ", pkg=" + r.packageInfo.getPackageName()
1591 + ", comp=" + r.intent.getComponent().toShortString()
1592 + ", dir=" + r.packageInfo.getAppDir());
1593
1594 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001595 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 appContext.init(r.packageInfo, r.token, this);
1597 appContext.setOuterContext(activity);
1598 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1599 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001600 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001601 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001602 activity.attach(appContext, this, getInstrumentation(), r.token,
1603 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001604 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001605
Christopher Tateb70f3df2009-04-07 16:07:59 -07001606 if (customIntent != null) {
1607 activity.mIntent = customIntent;
1608 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001609 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 activity.mStartedActivity = false;
1611 int theme = r.activityInfo.getThemeResource();
1612 if (theme != 0) {
1613 activity.setTheme(theme);
1614 }
1615
1616 activity.mCalled = false;
1617 mInstrumentation.callActivityOnCreate(activity, r.state);
1618 if (!activity.mCalled) {
1619 throw new SuperNotCalledException(
1620 "Activity " + r.intent.getComponent().toShortString() +
1621 " did not call through to super.onCreate()");
1622 }
1623 r.activity = activity;
1624 r.stopped = true;
1625 if (!r.activity.mFinished) {
1626 activity.performStart();
1627 r.stopped = false;
1628 }
1629 if (!r.activity.mFinished) {
1630 if (r.state != null) {
1631 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1632 }
1633 }
1634 if (!r.activity.mFinished) {
1635 activity.mCalled = false;
1636 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1637 if (!activity.mCalled) {
1638 throw new SuperNotCalledException(
1639 "Activity " + r.intent.getComponent().toShortString() +
1640 " did not call through to super.onPostCreate()");
1641 }
1642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644 r.paused = true;
1645
1646 mActivities.put(r.token, r);
1647
1648 } catch (SuperNotCalledException e) {
1649 throw e;
1650
1651 } catch (Exception e) {
1652 if (!mInstrumentation.onException(activity, e)) {
1653 throw new RuntimeException(
1654 "Unable to start activity " + component
1655 + ": " + e.toString(), e);
1656 }
1657 }
1658
1659 return activity;
1660 }
1661
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001662 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 // If we are getting ready to gc after going to the background, well
1664 // we are back active so skip it.
1665 unscheduleGcIdler();
1666
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001667 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001669 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670
1671 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001672 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001673 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 handleResumeActivity(r.token, false, r.isForward);
1675
1676 if (!r.activity.mFinished && r.startsNotResumed) {
1677 // The activity manager actually wants this one to start out
1678 // paused, because it needs to be visible but isn't in the
1679 // foreground. We accomplish this by going through the
1680 // normal startup (because activities expect to go through
1681 // onResume() the first time they run, before their window
1682 // is displayed), and then pausing it. However, in this case
1683 // we do -not- need to do the full pause cycle (of freezing
1684 // and such) because the activity manager assumes it can just
1685 // retain the current state it has.
1686 try {
1687 r.activity.mCalled = false;
1688 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001689 // We need to keep around the original state, in case
1690 // we need to be created again.
1691 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 if (!r.activity.mCalled) {
1693 throw new SuperNotCalledException(
1694 "Activity " + r.intent.getComponent().toShortString() +
1695 " did not call through to super.onPause()");
1696 }
1697
1698 } catch (SuperNotCalledException e) {
1699 throw e;
1700
1701 } catch (Exception e) {
1702 if (!mInstrumentation.onException(r.activity, e)) {
1703 throw new RuntimeException(
1704 "Unable to pause activity "
1705 + r.intent.getComponent().toShortString()
1706 + ": " + e.toString(), e);
1707 }
1708 }
1709 r.paused = true;
1710 }
1711 } else {
1712 // If there was an error, for any reason, tell the activity
1713 // manager to stop us.
1714 try {
1715 ActivityManagerNative.getDefault()
1716 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1717 } catch (RemoteException ex) {
1718 }
1719 }
1720 }
1721
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001722 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 List<Intent> intents) {
1724 final int N = intents.size();
1725 for (int i=0; i<N; i++) {
1726 Intent intent = intents.get(i);
1727 intent.setExtrasClassLoader(r.activity.getClassLoader());
1728 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1729 }
1730 }
1731
1732 public final void performNewIntents(IBinder token,
1733 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001734 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 if (r != null) {
1736 final boolean resumed = !r.paused;
1737 if (resumed) {
1738 mInstrumentation.callActivityOnPause(r.activity);
1739 }
1740 deliverNewIntents(r, intents);
1741 if (resumed) {
1742 mInstrumentation.callActivityOnResume(r.activity);
1743 }
1744 }
1745 }
Bob Leee5408332009-09-04 18:31:17 -07001746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 private final void handleNewIntent(NewIntentData data) {
1748 performNewIntents(data.token, data.intents);
1749 }
1750
1751 private final void handleReceiver(ReceiverData data) {
1752 // If we are getting ready to gc after going to the background, well
1753 // we are back active so skip it.
1754 unscheduleGcIdler();
1755
1756 String component = data.intent.getComponent().getClassName();
1757
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001758 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 data.info.applicationInfo);
1760
1761 IActivityManager mgr = ActivityManagerNative.getDefault();
1762
1763 BroadcastReceiver receiver = null;
1764 try {
1765 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1766 data.intent.setExtrasClassLoader(cl);
1767 if (data.resultExtras != null) {
1768 data.resultExtras.setClassLoader(cl);
1769 }
1770 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1771 } catch (Exception e) {
1772 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001773 if (DEBUG_BROADCAST) Slog.i(TAG,
1774 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1776 data.resultData, data.resultExtras, data.resultAbort);
1777 } catch (RemoteException ex) {
1778 }
1779 throw new RuntimeException(
1780 "Unable to instantiate receiver " + component
1781 + ": " + e.toString(), e);
1782 }
1783
1784 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001785 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001786
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001787 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 TAG, "Performing receive of " + data.intent
1789 + ": app=" + app
1790 + ", appName=" + app.getPackageName()
1791 + ", pkg=" + packageInfo.getPackageName()
1792 + ", comp=" + data.intent.getComponent().toShortString()
1793 + ", dir=" + packageInfo.getAppDir());
1794
Dianne Hackborn21556372010-02-04 16:34:40 -08001795 ContextImpl context = (ContextImpl)app.getBaseContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 receiver.setOrderedHint(true);
1797 receiver.setResult(data.resultCode, data.resultData,
1798 data.resultExtras);
1799 receiver.setOrderedHint(data.sync);
1800 receiver.onReceive(context.getReceiverRestrictedContext(),
1801 data.intent);
1802 } catch (Exception e) {
1803 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001804 if (DEBUG_BROADCAST) Slog.i(TAG,
1805 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1807 data.resultData, data.resultExtras, data.resultAbort);
1808 } catch (RemoteException ex) {
1809 }
1810 if (!mInstrumentation.onException(receiver, e)) {
1811 throw new RuntimeException(
1812 "Unable to start receiver " + component
1813 + ": " + e.toString(), e);
1814 }
1815 }
1816
1817 try {
1818 if (data.sync) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001819 if (DEBUG_BROADCAST) Slog.i(TAG,
1820 "Finishing ordered broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 mgr.finishReceiver(
1822 mAppThread.asBinder(), receiver.getResultCode(),
1823 receiver.getResultData(), receiver.getResultExtras(false),
1824 receiver.getAbortBroadcast());
1825 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001826 if (DEBUG_BROADCAST) Slog.i(TAG,
1827 "Finishing broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
1829 }
1830 } catch (RemoteException ex) {
1831 }
1832 }
1833
Christopher Tate181fafa2009-05-14 11:12:14 -07001834 // Instantiate a BackupAgent and tell it that it's alive
1835 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001836 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001837
1838 // no longer idle; we have backup work to do
1839 unscheduleGcIdler();
1840
1841 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001842 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001843 String packageName = packageInfo.mPackageName;
1844 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001845 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001846 + " already exists");
1847 return;
1848 }
Bob Leee5408332009-09-04 18:31:17 -07001849
Christopher Tate181fafa2009-05-14 11:12:14 -07001850 BackupAgent agent = null;
1851 String classname = data.appInfo.backupAgentName;
1852 if (classname == null) {
1853 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001854 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001855 + packageName);
1856 return;
1857 }
1858 classname = "android.app.FullBackupAgent";
1859 }
1860 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001861 IBinder binder = null;
1862 try {
1863 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1864 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1865
1866 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001867 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001868 + data.appInfo.backupAgentName);
1869
Dianne Hackborn21556372010-02-04 16:34:40 -08001870 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001871 context.init(packageInfo, null, this);
1872 context.setOuterContext(agent);
1873 agent.attach(context);
1874
1875 agent.onCreate();
1876 binder = agent.onBind();
1877 mBackupAgents.put(packageName, agent);
1878 } catch (Exception e) {
1879 // If this is during restore, fail silently; otherwise go
1880 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001881 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001882 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1883 throw e;
1884 }
1885 // falling through with 'binder' still null
1886 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001887
1888 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001889 try {
1890 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1891 } catch (RemoteException e) {
1892 // nothing to do.
1893 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001894 } catch (Exception e) {
1895 throw new RuntimeException("Unable to create BackupAgent "
1896 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1897 }
1898 }
1899
1900 // Tear down a BackupAgent
1901 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001902 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001903
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001904 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001905 String packageName = packageInfo.mPackageName;
1906 BackupAgent agent = mBackupAgents.get(packageName);
1907 if (agent != null) {
1908 try {
1909 agent.onDestroy();
1910 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001911 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001912 e.printStackTrace();
1913 }
1914 mBackupAgents.remove(packageName);
1915 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001916 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001917 }
1918 }
1919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 private final void handleCreateService(CreateServiceData data) {
1921 // If we are getting ready to gc after going to the background, well
1922 // we are back active so skip it.
1923 unscheduleGcIdler();
1924
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001925 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 data.info.applicationInfo);
1927 Service service = null;
1928 try {
1929 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1930 service = (Service) cl.loadClass(data.info.name).newInstance();
1931 } catch (Exception e) {
1932 if (!mInstrumentation.onException(service, e)) {
1933 throw new RuntimeException(
1934 "Unable to instantiate service " + data.info.name
1935 + ": " + e.toString(), e);
1936 }
1937 }
1938
1939 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001940 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941
Dianne Hackborn21556372010-02-04 16:34:40 -08001942 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 context.init(packageInfo, null, this);
1944
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001945 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 context.setOuterContext(service);
1947 service.attach(context, this, data.info.name, data.token, app,
1948 ActivityManagerNative.getDefault());
1949 service.onCreate();
1950 mServices.put(data.token, service);
1951 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001952 ActivityManagerNative.getDefault().serviceDoneExecuting(
1953 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 } catch (RemoteException e) {
1955 // nothing to do.
1956 }
1957 } catch (Exception e) {
1958 if (!mInstrumentation.onException(service, e)) {
1959 throw new RuntimeException(
1960 "Unable to create service " + data.info.name
1961 + ": " + e.toString(), e);
1962 }
1963 }
1964 }
1965
1966 private final void handleBindService(BindServiceData data) {
1967 Service s = mServices.get(data.token);
1968 if (s != null) {
1969 try {
1970 data.intent.setExtrasClassLoader(s.getClassLoader());
1971 try {
1972 if (!data.rebind) {
1973 IBinder binder = s.onBind(data.intent);
1974 ActivityManagerNative.getDefault().publishService(
1975 data.token, data.intent, binder);
1976 } else {
1977 s.onRebind(data.intent);
1978 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001979 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001981 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 } catch (RemoteException ex) {
1983 }
1984 } catch (Exception e) {
1985 if (!mInstrumentation.onException(s, e)) {
1986 throw new RuntimeException(
1987 "Unable to bind to service " + s
1988 + " with " + data.intent + ": " + e.toString(), e);
1989 }
1990 }
1991 }
1992 }
1993
1994 private final void handleUnbindService(BindServiceData data) {
1995 Service s = mServices.get(data.token);
1996 if (s != null) {
1997 try {
1998 data.intent.setExtrasClassLoader(s.getClassLoader());
1999 boolean doRebind = s.onUnbind(data.intent);
2000 try {
2001 if (doRebind) {
2002 ActivityManagerNative.getDefault().unbindFinished(
2003 data.token, data.intent, doRebind);
2004 } else {
2005 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002006 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008 } catch (RemoteException ex) {
2009 }
2010 } catch (Exception e) {
2011 if (!mInstrumentation.onException(s, e)) {
2012 throw new RuntimeException(
2013 "Unable to unbind to service " + s
2014 + " with " + data.intent + ": " + e.toString(), e);
2015 }
2016 }
2017 }
2018 }
2019
2020 private void handleDumpService(DumpServiceInfo info) {
2021 try {
2022 Service s = mServices.get(info.service);
2023 if (s != null) {
2024 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2025 s.dump(info.fd, pw, info.args);
2026 pw.close();
2027 }
2028 } finally {
2029 synchronized (info) {
2030 info.dumped = true;
2031 info.notifyAll();
2032 }
2033 }
2034 }
2035
2036 private final void handleServiceArgs(ServiceArgsData data) {
2037 Service s = mServices.get(data.token);
2038 if (s != null) {
2039 try {
2040 if (data.args != null) {
2041 data.args.setExtrasClassLoader(s.getClassLoader());
2042 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002043 int res = s.onStartCommand(data.args, data.flags, data.startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002045 ActivityManagerNative.getDefault().serviceDoneExecuting(
2046 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 } catch (RemoteException e) {
2048 // nothing to do.
2049 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002050 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 } catch (Exception e) {
2052 if (!mInstrumentation.onException(s, e)) {
2053 throw new RuntimeException(
2054 "Unable to start service " + s
2055 + " with " + data.args + ": " + e.toString(), e);
2056 }
2057 }
2058 }
2059 }
2060
2061 private final void handleStopService(IBinder token) {
2062 Service s = mServices.remove(token);
2063 if (s != null) {
2064 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002065 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 s.onDestroy();
2067 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002068 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002070 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002073 ActivityManagerNative.getDefault().serviceDoneExecuting(
2074 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 } catch (RemoteException e) {
2076 // nothing to do.
2077 }
2078 } catch (Exception e) {
2079 if (!mInstrumentation.onException(s, e)) {
2080 throw new RuntimeException(
2081 "Unable to stop service " + s
2082 + ": " + e.toString(), e);
2083 }
2084 }
2085 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002086 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 }
2088
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002089 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002091 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002092 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 + " finished=" + r.activity.mFinished);
2094 if (r != null && !r.activity.mFinished) {
2095 if (clearHide) {
2096 r.hideForNow = false;
2097 r.activity.mStartedActivity = false;
2098 }
2099 try {
2100 if (r.pendingIntents != null) {
2101 deliverNewIntents(r, r.pendingIntents);
2102 r.pendingIntents = null;
2103 }
2104 if (r.pendingResults != null) {
2105 deliverResults(r, r.pendingResults);
2106 r.pendingResults = null;
2107 }
2108 r.activity.performResume();
2109
Bob Leee5408332009-09-04 18:31:17 -07002110 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 r.paused = false;
2114 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 r.state = null;
2116 } catch (Exception e) {
2117 if (!mInstrumentation.onException(r.activity, e)) {
2118 throw new RuntimeException(
2119 "Unable to resume activity "
2120 + r.intent.getComponent().toShortString()
2121 + ": " + e.toString(), e);
2122 }
2123 }
2124 }
2125 return r;
2126 }
2127
2128 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2129 // If we are getting ready to gc after going to the background, well
2130 // we are back active so skip it.
2131 unscheduleGcIdler();
2132
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002133 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134
2135 if (r != null) {
2136 final Activity a = r.activity;
2137
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002138 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 TAG, "Resume " + r + " started activity: " +
2140 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2141 + ", finished: " + a.mFinished);
2142
2143 final int forwardBit = isForward ?
2144 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 // If the window hasn't yet been added to the window manager,
2147 // and this guy didn't finish itself or start another activity,
2148 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002149 boolean willBeVisible = !a.mStartedActivity;
2150 if (!willBeVisible) {
2151 try {
2152 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2153 a.getActivityToken());
2154 } catch (RemoteException e) {
2155 }
2156 }
2157 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 r.window = r.activity.getWindow();
2159 View decor = r.window.getDecorView();
2160 decor.setVisibility(View.INVISIBLE);
2161 ViewManager wm = a.getWindowManager();
2162 WindowManager.LayoutParams l = r.window.getAttributes();
2163 a.mDecor = decor;
2164 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2165 l.softInputMode |= forwardBit;
2166 if (a.mVisibleFromClient) {
2167 a.mWindowAdded = true;
2168 wm.addView(decor, l);
2169 }
2170
2171 // If the window has already been added, but during resume
2172 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002173 // window visible.
2174 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002175 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 TAG, "Launch " + r + " mStartedActivity set");
2177 r.hideForNow = true;
2178 }
2179
2180 // The window is now visible if it has been added, we are not
2181 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002182 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002183 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002185 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002186 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 performConfigurationChanged(r.activity, r.newConfig);
2188 r.newConfig = null;
2189 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002190 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 + isForward);
2192 WindowManager.LayoutParams l = r.window.getAttributes();
2193 if ((l.softInputMode
2194 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2195 != forwardBit) {
2196 l.softInputMode = (l.softInputMode
2197 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2198 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002199 if (r.activity.mVisibleFromClient) {
2200 ViewManager wm = a.getWindowManager();
2201 View decor = r.window.getDecorView();
2202 wm.updateViewLayout(decor, l);
2203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 }
2205 r.activity.mVisibleFromServer = true;
2206 mNumVisibleActivities++;
2207 if (r.activity.mVisibleFromClient) {
2208 r.activity.makeVisible();
2209 }
2210 }
2211
2212 r.nextIdle = mNewActivities;
2213 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002214 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 TAG, "Scheduling idle handler for " + r);
2216 Looper.myQueue().addIdleHandler(new Idler());
2217
2218 } else {
2219 // If an exception was thrown when trying to resume, then
2220 // just end this activity.
2221 try {
2222 ActivityManagerNative.getDefault()
2223 .finishActivity(token, Activity.RESULT_CANCELED, null);
2224 } catch (RemoteException ex) {
2225 }
2226 }
2227 }
2228
2229 private int mThumbnailWidth = -1;
2230 private int mThumbnailHeight = -1;
2231
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002232 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 Bitmap thumbnail = null;
2234 try {
2235 int w = mThumbnailWidth;
2236 int h;
2237 if (w < 0) {
2238 Resources res = r.activity.getResources();
2239 mThumbnailHeight = h =
2240 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2241
2242 mThumbnailWidth = w =
2243 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2244 } else {
2245 h = mThumbnailHeight;
2246 }
2247
2248 // XXX Only set hasAlpha if needed?
2249 thumbnail = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
2250 thumbnail.eraseColor(0);
2251 Canvas cv = new Canvas(thumbnail);
2252 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2253 thumbnail = null;
2254 }
2255 } catch (Exception e) {
2256 if (!mInstrumentation.onException(r.activity, e)) {
2257 throw new RuntimeException(
2258 "Unable to create thumbnail of "
2259 + r.intent.getComponent().toShortString()
2260 + ": " + e.toString(), e);
2261 }
2262 thumbnail = null;
2263 }
2264
2265 return thumbnail;
2266 }
2267
2268 private final void handlePauseActivity(IBinder token, boolean finished,
2269 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002270 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002272 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 if (userLeaving) {
2274 performUserLeavingActivity(r);
2275 }
Bob Leee5408332009-09-04 18:31:17 -07002276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 r.activity.mConfigChangeFlags |= configChanges;
2278 Bundle state = performPauseActivity(token, finished, true);
2279
2280 // Tell the activity manager we have paused.
2281 try {
2282 ActivityManagerNative.getDefault().activityPaused(token, state);
2283 } catch (RemoteException ex) {
2284 }
2285 }
2286 }
2287
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002288 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 mInstrumentation.callActivityOnUserLeaving(r.activity);
2290 }
2291
2292 final Bundle performPauseActivity(IBinder token, boolean finished,
2293 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002294 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 return r != null ? performPauseActivity(r, finished, saveState) : null;
2296 }
2297
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002298 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 boolean saveState) {
2300 if (r.paused) {
2301 if (r.activity.mFinished) {
2302 // If we are finishing, we won't call onResume() in certain cases.
2303 // So here we likewise don't want to call onPause() if the activity
2304 // isn't resumed.
2305 return null;
2306 }
2307 RuntimeException e = new RuntimeException(
2308 "Performing pause of activity that is not resumed: "
2309 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002310 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 }
2312 Bundle state = null;
2313 if (finished) {
2314 r.activity.mFinished = true;
2315 }
2316 try {
2317 // Next have the activity save its current state and managed dialogs...
2318 if (!r.activity.mFinished && saveState) {
2319 state = new Bundle();
2320 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2321 r.state = state;
2322 }
2323 // Now we are idle.
2324 r.activity.mCalled = false;
2325 mInstrumentation.callActivityOnPause(r.activity);
2326 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2327 if (!r.activity.mCalled) {
2328 throw new SuperNotCalledException(
2329 "Activity " + r.intent.getComponent().toShortString() +
2330 " did not call through to super.onPause()");
2331 }
2332
2333 } catch (SuperNotCalledException e) {
2334 throw e;
2335
2336 } catch (Exception e) {
2337 if (!mInstrumentation.onException(r.activity, e)) {
2338 throw new RuntimeException(
2339 "Unable to pause activity "
2340 + r.intent.getComponent().toShortString()
2341 + ": " + e.toString(), e);
2342 }
2343 }
2344 r.paused = true;
2345 return state;
2346 }
2347
2348 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002349 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 performStopActivityInner(r, null, false);
2351 }
2352
2353 private static class StopInfo {
2354 Bitmap thumbnail;
2355 CharSequence description;
2356 }
2357
2358 private final class ProviderRefCount {
2359 public int count;
2360 ProviderRefCount(int pCount) {
2361 count = pCount;
2362 }
2363 }
2364
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002365 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002367 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 if (r != null) {
2369 if (!keepShown && r.stopped) {
2370 if (r.activity.mFinished) {
2371 // If we are finishing, we won't call onResume() in certain
2372 // cases. So here we likewise don't want to call onStop()
2373 // if the activity isn't resumed.
2374 return;
2375 }
2376 RuntimeException e = new RuntimeException(
2377 "Performing stop of activity that is not resumed: "
2378 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002379 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 }
2381
2382 if (info != null) {
2383 try {
2384 // First create a thumbnail for the activity...
2385 //info.thumbnail = createThumbnailBitmap(r);
2386 info.description = r.activity.onCreateDescription();
2387 } catch (Exception e) {
2388 if (!mInstrumentation.onException(r.activity, e)) {
2389 throw new RuntimeException(
2390 "Unable to save state of activity "
2391 + r.intent.getComponent().toShortString()
2392 + ": " + e.toString(), e);
2393 }
2394 }
2395 }
2396
2397 if (!keepShown) {
2398 try {
2399 // Now we are idle.
2400 r.activity.performStop();
2401 } catch (Exception e) {
2402 if (!mInstrumentation.onException(r.activity, e)) {
2403 throw new RuntimeException(
2404 "Unable to stop activity "
2405 + r.intent.getComponent().toShortString()
2406 + ": " + e.toString(), e);
2407 }
2408 }
2409 r.stopped = true;
2410 }
2411
2412 r.paused = true;
2413 }
2414 }
2415
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002416 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 View v = r.activity.mDecor;
2418 if (v != null) {
2419 if (show) {
2420 if (!r.activity.mVisibleFromServer) {
2421 r.activity.mVisibleFromServer = true;
2422 mNumVisibleActivities++;
2423 if (r.activity.mVisibleFromClient) {
2424 r.activity.makeVisible();
2425 }
2426 }
2427 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002428 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002429 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 performConfigurationChanged(r.activity, r.newConfig);
2431 r.newConfig = null;
2432 }
2433 } else {
2434 if (r.activity.mVisibleFromServer) {
2435 r.activity.mVisibleFromServer = false;
2436 mNumVisibleActivities--;
2437 v.setVisibility(View.INVISIBLE);
2438 }
2439 }
2440 }
2441 }
2442
2443 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002444 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 r.activity.mConfigChangeFlags |= configChanges;
2446
2447 StopInfo info = new StopInfo();
2448 performStopActivityInner(r, info, show);
2449
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002450 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 TAG, "Finishing stop of " + r + ": show=" + show
2452 + " win=" + r.window);
2453
2454 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 // Tell activity manager we have been stopped.
2457 try {
2458 ActivityManagerNative.getDefault().activityStopped(
2459 r.token, info.thumbnail, info.description);
2460 } catch (RemoteException ex) {
2461 }
2462 }
2463
2464 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002465 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 if (r.stopped) {
2467 r.activity.performRestart();
2468 r.stopped = false;
2469 }
2470 }
2471
2472 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002473 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 if (!show && !r.stopped) {
2475 performStopActivityInner(r, null, show);
2476 } else if (show && r.stopped) {
2477 // If we are getting ready to gc after going to the background, well
2478 // we are back active so skip it.
2479 unscheduleGcIdler();
2480
2481 r.activity.performRestart();
2482 r.stopped = false;
2483 }
2484 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002485 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 TAG, "Handle window " + r + " visibility: " + show);
2487 updateVisibility(r, show);
2488 }
2489 }
2490
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002491 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 final int N = results.size();
2493 for (int i=0; i<N; i++) {
2494 ResultInfo ri = results.get(i);
2495 try {
2496 if (ri.mData != null) {
2497 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2498 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002499 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002500 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 r.activity.dispatchActivityResult(ri.mResultWho,
2502 ri.mRequestCode, ri.mResultCode, ri.mData);
2503 } catch (Exception e) {
2504 if (!mInstrumentation.onException(r.activity, e)) {
2505 throw new RuntimeException(
2506 "Failure delivering result " + ri + " to activity "
2507 + r.intent.getComponent().toShortString()
2508 + ": " + e.toString(), e);
2509 }
2510 }
2511 }
2512 }
2513
2514 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002515 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002516 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 if (r != null) {
2518 final boolean resumed = !r.paused;
2519 if (!r.activity.mFinished && r.activity.mDecor != null
2520 && r.hideForNow && resumed) {
2521 // We had hidden the activity because it started another
2522 // one... we have gotten a result back and we are not
2523 // paused, so make sure our window is visible.
2524 updateVisibility(r, true);
2525 }
2526 if (resumed) {
2527 try {
2528 // Now we are idle.
2529 r.activity.mCalled = false;
2530 mInstrumentation.callActivityOnPause(r.activity);
2531 if (!r.activity.mCalled) {
2532 throw new SuperNotCalledException(
2533 "Activity " + r.intent.getComponent().toShortString()
2534 + " did not call through to super.onPause()");
2535 }
2536 } catch (SuperNotCalledException e) {
2537 throw e;
2538 } catch (Exception e) {
2539 if (!mInstrumentation.onException(r.activity, e)) {
2540 throw new RuntimeException(
2541 "Unable to pause activity "
2542 + r.intent.getComponent().toShortString()
2543 + ": " + e.toString(), e);
2544 }
2545 }
2546 }
2547 deliverResults(r, res.results);
2548 if (resumed) {
2549 mInstrumentation.callActivityOnResume(r.activity);
2550 }
2551 }
2552 }
2553
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002554 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 return performDestroyActivity(token, finishing, 0, false);
2556 }
2557
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002558 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002560 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002561 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 if (r != null) {
2563 r.activity.mConfigChangeFlags |= configChanges;
2564 if (finishing) {
2565 r.activity.mFinished = true;
2566 }
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05002567 if (getNonConfigInstance) {
2568 r.activity.mChangingConfigurations = true;
2569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 if (!r.paused) {
2571 try {
2572 r.activity.mCalled = false;
2573 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002574 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 r.activity.getComponentName().getClassName());
2576 if (!r.activity.mCalled) {
2577 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002578 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 + " 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 "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002587 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 + ": " + e.toString(), e);
2589 }
2590 }
2591 r.paused = true;
2592 }
2593 if (!r.stopped) {
2594 try {
2595 r.activity.performStop();
2596 } catch (SuperNotCalledException e) {
2597 throw e;
2598 } catch (Exception e) {
2599 if (!mInstrumentation.onException(r.activity, e)) {
2600 throw new RuntimeException(
2601 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002602 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 + ": " + e.toString(), e);
2604 }
2605 }
2606 r.stopped = true;
2607 }
2608 if (getNonConfigInstance) {
2609 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002610 r.lastNonConfigurationInstances
2611 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 } catch (Exception e) {
2613 if (!mInstrumentation.onException(r.activity, e)) {
2614 throw new RuntimeException(
2615 "Unable to retain activity "
2616 + r.intent.getComponent().toShortString()
2617 + ": " + e.toString(), e);
2618 }
2619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 }
2621 try {
2622 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002623 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 if (!r.activity.mCalled) {
2625 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002626 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 " did not call through to super.onDestroy()");
2628 }
2629 if (r.window != null) {
2630 r.window.closeAllPanels();
2631 }
2632 } catch (SuperNotCalledException e) {
2633 throw e;
2634 } catch (Exception e) {
2635 if (!mInstrumentation.onException(r.activity, e)) {
2636 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002637 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2638 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 }
2640 }
2641 }
2642 mActivities.remove(token);
2643
2644 return r;
2645 }
2646
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002647 private static String safeToComponentShortString(Intent intent) {
2648 ComponentName component = intent.getComponent();
2649 return component == null ? "[Unknown]" : component.toShortString();
2650 }
2651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 private final void handleDestroyActivity(IBinder token, boolean finishing,
2653 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002654 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 configChanges, getNonConfigInstance);
2656 if (r != null) {
2657 WindowManager wm = r.activity.getWindowManager();
2658 View v = r.activity.mDecor;
2659 if (v != null) {
2660 if (r.activity.mVisibleFromServer) {
2661 mNumVisibleActivities--;
2662 }
2663 IBinder wtoken = v.getWindowToken();
2664 if (r.activity.mWindowAdded) {
2665 wm.removeViewImmediate(v);
2666 }
2667 if (wtoken != null) {
2668 WindowManagerImpl.getDefault().closeAll(wtoken,
2669 r.activity.getClass().getName(), "Activity");
2670 }
2671 r.activity.mDecor = null;
2672 }
2673 WindowManagerImpl.getDefault().closeAll(token,
2674 r.activity.getClass().getName(), "Activity");
2675
2676 // Mocked out contexts won't be participating in the normal
2677 // process lifecycle, but if we're running with a proper
2678 // ApplicationContext we need to have it tear down things
2679 // cleanly.
2680 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002681 if (c instanceof ContextImpl) {
2682 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 r.activity.getClass().getName(), "Activity");
2684 }
2685 }
2686 if (finishing) {
2687 try {
2688 ActivityManagerNative.getDefault().activityDestroyed(token);
2689 } catch (RemoteException ex) {
2690 // If the system process has died, it's game over for everyone.
2691 }
2692 }
2693 }
2694
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002695 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 // If we are getting ready to gc after going to the background, well
2697 // we are back active so skip it.
2698 unscheduleGcIdler();
2699
2700 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002701
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002702 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002703 + tmp.token + " with configChanges=0x"
2704 + Integer.toHexString(configChanges));
2705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 // First: make sure we have the most recent configuration and most
2707 // recent version of the activity, or skip it if some previous call
2708 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002709 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 int N = mRelaunchingActivities.size();
2711 IBinder token = tmp.token;
2712 tmp = null;
2713 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002714 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 if (r.token == token) {
2716 tmp = r;
2717 mRelaunchingActivities.remove(i);
2718 i--;
2719 N--;
2720 }
2721 }
Bob Leee5408332009-09-04 18:31:17 -07002722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002724 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 return;
2726 }
Bob Leee5408332009-09-04 18:31:17 -07002727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 if (mPendingConfiguration != null) {
2729 changedConfig = mPendingConfiguration;
2730 mPendingConfiguration = null;
2731 }
2732 }
Bob Leee5408332009-09-04 18:31:17 -07002733
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002734 if (tmp.createdConfig != null) {
2735 // If the activity manager is passing us its current config,
2736 // assume that is really what we want regardless of what we
2737 // may have pending.
2738 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002739 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2740 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2741 if (changedConfig == null
2742 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2743 changedConfig = tmp.createdConfig;
2744 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002745 }
2746 }
2747
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 + ": changedConfig=" + changedConfig);
2750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 // If there was a pending configuration change, execute it first.
2752 if (changedConfig != null) {
2753 handleConfigurationChanged(changedConfig);
2754 }
Bob Leee5408332009-09-04 18:31:17 -07002755
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002756 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002757 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 if (r == null) {
2759 return;
2760 }
Bob Leee5408332009-09-04 18:31:17 -07002761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002763 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 Bundle savedState = null;
2766 if (!r.paused) {
2767 savedState = performPauseActivity(r.token, false, true);
2768 }
Bob Leee5408332009-09-04 18:31:17 -07002769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 r.activity = null;
2773 r.window = null;
2774 r.hideForNow = false;
2775 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002776 // Merge any pending results and pending intents; don't just replace them
2777 if (tmp.pendingResults != null) {
2778 if (r.pendingResults == null) {
2779 r.pendingResults = tmp.pendingResults;
2780 } else {
2781 r.pendingResults.addAll(tmp.pendingResults);
2782 }
2783 }
2784 if (tmp.pendingIntents != null) {
2785 if (r.pendingIntents == null) {
2786 r.pendingIntents = tmp.pendingIntents;
2787 } else {
2788 r.pendingIntents.addAll(tmp.pendingIntents);
2789 }
2790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 r.startsNotResumed = tmp.startsNotResumed;
2792 if (savedState != null) {
2793 r.state = savedState;
2794 }
Bob Leee5408332009-09-04 18:31:17 -07002795
Christopher Tateb70f3df2009-04-07 16:07:59 -07002796 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 }
2798
2799 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002800 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 Bitmap thumbnail = createThumbnailBitmap(r);
2802 CharSequence description = null;
2803 try {
2804 description = r.activity.onCreateDescription();
2805 } catch (Exception e) {
2806 if (!mInstrumentation.onException(r.activity, e)) {
2807 throw new RuntimeException(
2808 "Unable to create description of activity "
2809 + r.intent.getComponent().toShortString()
2810 + ": " + e.toString(), e);
2811 }
2812 }
2813 //System.out.println("Reporting top thumbnail " + thumbnail);
2814 try {
2815 ActivityManagerNative.getDefault().reportThumbnail(
2816 token, thumbnail, description);
2817 } catch (RemoteException ex) {
2818 }
2819 }
2820
2821 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2822 boolean allActivities, Configuration newConfig) {
2823 ArrayList<ComponentCallbacks> callbacks
2824 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002827 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002829 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 Activity a = ar.activity;
2831 if (a != null) {
2832 if (!ar.activity.mFinished && (allActivities ||
2833 (a != null && !ar.paused))) {
2834 // If the activity is currently resumed, its configuration
2835 // needs to change right now.
2836 callbacks.add(a);
2837 } else if (newConfig != null) {
2838 // Otherwise, we will tell it about the change
2839 // the next time it is resumed or shown. Note that
2840 // the activity manager may, before then, decide the
2841 // activity needs to be destroyed to handle its new
2842 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002843 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002844 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 ar.newConfig = newConfig;
2846 }
2847 }
2848 }
2849 }
2850 if (mServices.size() > 0) {
2851 Iterator<Service> it = mServices.values().iterator();
2852 while (it.hasNext()) {
2853 callbacks.add(it.next());
2854 }
2855 }
2856 synchronized (mProviderMap) {
2857 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002858 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 while (it.hasNext()) {
2860 callbacks.add(it.next().mLocalProvider);
2861 }
2862 }
2863 }
2864 final int N = mAllApplications.size();
2865 for (int i=0; i<N; i++) {
2866 callbacks.add(mAllApplications.get(i));
2867 }
Bob Leee5408332009-09-04 18:31:17 -07002868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 return callbacks;
2870 }
Bob Leee5408332009-09-04 18:31:17 -07002871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 private final void performConfigurationChanged(
2873 ComponentCallbacks cb, Configuration config) {
2874 // Only for Activity objects, check that they actually call up to their
2875 // superclass implementation. ComponentCallbacks is an interface, so
2876 // we check the runtime type and act accordingly.
2877 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2878 if (activity != null) {
2879 activity.mCalled = false;
2880 }
Bob Leee5408332009-09-04 18:31:17 -07002881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 boolean shouldChangeConfig = false;
2883 if ((activity == null) || (activity.mCurrentConfig == null)) {
2884 shouldChangeConfig = true;
2885 } else {
Bob Leee5408332009-09-04 18:31:17 -07002886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 // If the new config is the same as the config this Activity
2888 // is already running with then don't bother calling
2889 // onConfigurationChanged
2890 int diff = activity.mCurrentConfig.diff(config);
2891 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 // If this activity doesn't handle any of the config changes
2894 // then don't bother calling onConfigurationChanged as we're
2895 // going to destroy it.
2896 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2897 shouldChangeConfig = true;
2898 }
2899 }
2900 }
Bob Leee5408332009-09-04 18:31:17 -07002901
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002902 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002903 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 if (shouldChangeConfig) {
2905 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 if (activity != null) {
2908 if (!activity.mCalled) {
2909 throw new SuperNotCalledException(
2910 "Activity " + activity.getLocalClassName() +
2911 " did not call through to super.onConfigurationChanged()");
2912 }
2913 activity.mConfigChangeFlags = 0;
2914 activity.mCurrentConfig = new Configuration(config);
2915 }
2916 }
2917 }
2918
Dianne Hackbornae078162010-03-18 11:29:37 -07002919 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002920 if (mResConfiguration == null) {
2921 mResConfiguration = new Configuration();
2922 }
2923 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002924 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002925 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002926 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002927 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002928 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002929 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002930
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002931 // set it for java, this also affects newly created Resources
2932 if (config.locale != null) {
2933 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 }
Bob Leee5408332009-09-04 18:31:17 -07002935
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002936 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07002937
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002938 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002939 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002940
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002941 Iterator<WeakReference<Resources>> it =
2942 mActiveResources.values().iterator();
2943 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
2944 // mActiveResources.entrySet().iterator();
2945 while (it.hasNext()) {
2946 WeakReference<Resources> v = it.next();
2947 Resources r = v.get();
2948 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002949 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002950 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002951 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002952 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002953 // + " " + r + ": " + r.getConfiguration());
2954 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002955 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002956 it.remove();
2957 }
2958 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002959
2960 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002961 }
2962
2963 final void handleConfigurationChanged(Configuration config) {
2964
2965 ArrayList<ComponentCallbacks> callbacks = null;
2966
2967 synchronized (mPackages) {
2968 if (mPendingConfiguration != null) {
2969 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
2970 config = mPendingConfiguration;
2971 }
2972 mPendingConfiguration = null;
2973 }
2974
2975 if (config == null) {
2976 return;
2977 }
2978
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002979 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002980 + config);
2981
2982 applyConfigurationToResourcesLocked(config);
2983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 if (mConfiguration == null) {
2985 mConfiguration = new Configuration();
2986 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002987 if (!mConfiguration.isOtherSeqNewer(config)) {
2988 return;
2989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07002991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 callbacks = collectComponentCallbacksLocked(false, config);
2993 }
Bob Leee5408332009-09-04 18:31:17 -07002994
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002995 if (callbacks != null) {
2996 final int N = callbacks.size();
2997 for (int i=0; i<N; i++) {
2998 performConfigurationChanged(callbacks.get(i), config);
2999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 }
3001 }
3002
3003 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003004 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 if (r == null || r.activity == null) {
3006 return;
3007 }
Bob Leee5408332009-09-04 18:31:17 -07003008
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003009 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003010 + r.activityInfo.name);
3011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 performConfigurationChanged(r.activity, mConfiguration);
3013 }
3014
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003015 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003016 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003017 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003018 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3019 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003020 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003021 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003022 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003023 } finally {
3024 try {
3025 pcd.fd.close();
3026 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003027 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003028 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003029 }
3030 } else {
3031 Debug.stopMethodTracing();
3032 }
3033 }
Bob Leee5408332009-09-04 18:31:17 -07003034
Andy McFadden824c5102010-07-09 16:26:57 -07003035 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3036 if (managed) {
3037 try {
3038 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3039 } catch (IOException e) {
3040 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3041 + " -- can the process access this path?");
3042 } finally {
3043 try {
3044 dhd.fd.close();
3045 } catch (IOException e) {
3046 Slog.w(TAG, "Failure closing profile fd", e);
3047 }
3048 }
3049 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003050 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003051 }
3052 }
3053
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003054 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3055 boolean hasPkgInfo = false;
3056 if (packages != null) {
3057 for (int i=packages.length-1; i>=0; i--) {
3058 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3059 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003060 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003061 ref = mPackages.get(packages[i]);
3062 if (ref != null && ref.get() != null) {
3063 hasPkgInfo = true;
3064 } else {
3065 ref = mResourcePackages.get(packages[i]);
3066 if (ref != null && ref.get() != null) {
3067 hasPkgInfo = true;
3068 }
3069 }
3070 }
3071 mPackages.remove(packages[i]);
3072 mResourcePackages.remove(packages[i]);
3073 }
3074 }
3075 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3076 hasPkgInfo);
3077 }
3078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 final void handleLowMemory() {
3080 ArrayList<ComponentCallbacks> callbacks
3081 = new ArrayList<ComponentCallbacks>();
3082
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003083 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 callbacks = collectComponentCallbacksLocked(true, null);
3085 }
Bob Leee5408332009-09-04 18:31:17 -07003086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 final int N = callbacks.size();
3088 for (int i=0; i<N; i++) {
3089 callbacks.get(i).onLowMemory();
3090 }
3091
Chris Tatece229052009-03-25 16:44:52 -07003092 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3093 if (Process.myUid() != Process.SYSTEM_UID) {
3094 int sqliteReleased = SQLiteDatabase.releaseMemory();
3095 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3096 }
Bob Leee5408332009-09-04 18:31:17 -07003097
Mike Reedcaf0df12009-04-27 14:32:05 -04003098 // Ask graphics to free up as much as possible (font/image caches)
3099 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100
3101 BinderInternal.forceGc("mem");
3102 }
3103
3104 private final void handleBindApplication(AppBindData data) {
3105 mBoundApplication = data;
3106 mConfiguration = new Configuration(data.config);
3107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003109 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 android.ddm.DdmHandleAppName.setAppName(data.processName);
3111
3112 /*
3113 * Before spawning a new process, reset the time zone to be the system time zone.
3114 * This needs to be done because the system time zone could have changed after the
3115 * the spawning of this process. Without doing this this process would have the incorrect
3116 * system time zone.
3117 */
3118 TimeZone.setDefault(null);
3119
3120 /*
3121 * Initialize the default locale in this process for the reasons we set the time zone.
3122 */
3123 Locale.setDefault(data.config.locale);
3124
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003125 /*
3126 * Update the system configuration since its preloaded and might not
3127 * reflect configuration changes. The configuration object passed
3128 * in AppBindData can be safely assumed to be up to date
3129 */
3130 Resources.getSystem().updateConfiguration(mConfiguration, null);
3131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 data.info = getPackageInfoNoCheck(data.appInfo);
3133
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003134 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003135 * For system applications on userdebug/eng builds, log stack
3136 * traces of disk and network access to dropbox for analysis.
3137 */
3138 if ((data.appInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0 &&
3139 !"user".equals(Build.TYPE)) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003140 StrictMode.setThreadBlockingPolicy(
3141 StrictMode.DISALLOW_DISK_WRITE |
3142 StrictMode.DISALLOW_DISK_READ |
3143 StrictMode.DISALLOW_NETWORK |
3144 StrictMode.PENALTY_DROPBOX);
3145 }
3146
3147 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003148 * Switch this process to density compatibility mode if needed.
3149 */
3150 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3151 == 0) {
3152 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3153 }
Bob Leee5408332009-09-04 18:31:17 -07003154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3156 // XXX should have option to change the port.
3157 Debug.changeDebugPort(8100);
3158 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003159 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 + " is waiting for the debugger on port 8100...");
3161
3162 IActivityManager mgr = ActivityManagerNative.getDefault();
3163 try {
3164 mgr.showWaitingForDebugger(mAppThread, true);
3165 } catch (RemoteException ex) {
3166 }
3167
3168 Debug.waitForDebugger();
3169
3170 try {
3171 mgr.showWaitingForDebugger(mAppThread, false);
3172 } catch (RemoteException ex) {
3173 }
3174
3175 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003176 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 + " can be debugged on port 8100...");
3178 }
3179 }
3180
3181 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003182 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 appContext.init(data.info, null, this);
3184 InstrumentationInfo ii = null;
3185 try {
3186 ii = appContext.getPackageManager().
3187 getInstrumentationInfo(data.instrumentationName, 0);
3188 } catch (PackageManager.NameNotFoundException e) {
3189 }
3190 if (ii == null) {
3191 throw new RuntimeException(
3192 "Unable to find instrumentation info for: "
3193 + data.instrumentationName);
3194 }
3195
3196 mInstrumentationAppDir = ii.sourceDir;
3197 mInstrumentationAppPackage = ii.packageName;
3198 mInstrumentedAppDir = data.info.getAppDir();
3199
3200 ApplicationInfo instrApp = new ApplicationInfo();
3201 instrApp.packageName = ii.packageName;
3202 instrApp.sourceDir = ii.sourceDir;
3203 instrApp.publicSourceDir = ii.publicSourceDir;
3204 instrApp.dataDir = ii.dataDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003205 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003207 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 instrContext.init(pi, null, this);
3209
3210 try {
3211 java.lang.ClassLoader cl = instrContext.getClassLoader();
3212 mInstrumentation = (Instrumentation)
3213 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3214 } catch (Exception e) {
3215 throw new RuntimeException(
3216 "Unable to instantiate instrumentation "
3217 + data.instrumentationName + ": " + e.toString(), e);
3218 }
3219
3220 mInstrumentation.init(this, instrContext, appContext,
3221 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3222
3223 if (data.profileFile != null && !ii.handleProfiling) {
3224 data.handlingProfiling = true;
3225 File file = new File(data.profileFile);
3226 file.getParentFile().mkdirs();
3227 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3228 }
3229
3230 try {
3231 mInstrumentation.onCreate(data.instrumentationArgs);
3232 }
3233 catch (Exception e) {
3234 throw new RuntimeException(
3235 "Exception thrown in onCreate() of "
3236 + data.instrumentationName + ": " + e.toString(), e);
3237 }
3238
3239 } else {
3240 mInstrumentation = new Instrumentation();
3241 }
3242
Christopher Tate181fafa2009-05-14 11:12:14 -07003243 // If the app is being launched for full backup or restore, bring it up in
3244 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003245 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 mInitialApplication = app;
3247
3248 List<ProviderInfo> providers = data.providers;
3249 if (providers != null) {
3250 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003251 // For process that contain content providers, we want to
3252 // ensure that the JIT is enabled "at some point".
3253 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 }
3255
3256 try {
3257 mInstrumentation.callApplicationOnCreate(app);
3258 } catch (Exception e) {
3259 if (!mInstrumentation.onException(app, e)) {
3260 throw new RuntimeException(
3261 "Unable to create application " + app.getClass().getName()
3262 + ": " + e.toString(), e);
3263 }
3264 }
3265 }
3266
3267 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3268 IActivityManager am = ActivityManagerNative.getDefault();
3269 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3270 Debug.stopMethodTracing();
3271 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003272 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 // + ", app thr: " + mAppThread);
3274 try {
3275 am.finishInstrumentation(mAppThread, resultCode, results);
3276 } catch (RemoteException ex) {
3277 }
3278 }
3279
3280 private final void installContentProviders(
3281 Context context, List<ProviderInfo> providers) {
3282 final ArrayList<IActivityManager.ContentProviderHolder> results =
3283 new ArrayList<IActivityManager.ContentProviderHolder>();
3284
3285 Iterator<ProviderInfo> i = providers.iterator();
3286 while (i.hasNext()) {
3287 ProviderInfo cpi = i.next();
3288 StringBuilder buf = new StringBuilder(128);
3289 buf.append("Publishing provider ");
3290 buf.append(cpi.authority);
3291 buf.append(": ");
3292 buf.append(cpi.name);
3293 Log.i(TAG, buf.toString());
3294 IContentProvider cp = installProvider(context, null, cpi, false);
3295 if (cp != null) {
3296 IActivityManager.ContentProviderHolder cph =
3297 new IActivityManager.ContentProviderHolder(cpi);
3298 cph.provider = cp;
3299 results.add(cph);
3300 // Don't ever unload this provider from the process.
3301 synchronized(mProviderMap) {
3302 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3303 }
3304 }
3305 }
3306
3307 try {
3308 ActivityManagerNative.getDefault().publishContentProviders(
3309 getApplicationThread(), results);
3310 } catch (RemoteException ex) {
3311 }
3312 }
3313
3314 private final IContentProvider getProvider(Context context, String name) {
3315 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003316 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 if (pr != null) {
3318 return pr.mProvider;
3319 }
3320 }
3321
3322 IActivityManager.ContentProviderHolder holder = null;
3323 try {
3324 holder = ActivityManagerNative.getDefault().getContentProvider(
3325 getApplicationThread(), name);
3326 } catch (RemoteException ex) {
3327 }
3328 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003329 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 return null;
3331 }
3332 if (holder.permissionFailure != null) {
3333 throw new SecurityException("Permission " + holder.permissionFailure
3334 + " required for provider " + name);
3335 }
3336
3337 IContentProvider prov = installProvider(context, holder.provider,
3338 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003339 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 if (holder.noReleaseNeeded || holder.provider == null) {
3341 // We are not going to release the provider if it is an external
3342 // provider that doesn't care about being released, or if it is
3343 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003344 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 synchronized(mProviderMap) {
3346 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3347 }
3348 }
3349 return prov;
3350 }
3351
3352 public final IContentProvider acquireProvider(Context c, String name) {
3353 IContentProvider provider = getProvider(c, name);
3354 if(provider == null)
3355 return null;
3356 IBinder jBinder = provider.asBinder();
3357 synchronized(mProviderMap) {
3358 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3359 if(prc == null) {
3360 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3361 } else {
3362 prc.count++;
3363 } //end else
3364 } //end synchronized
3365 return provider;
3366 }
3367
3368 public final boolean releaseProvider(IContentProvider provider) {
3369 if(provider == null) {
3370 return false;
3371 }
3372 IBinder jBinder = provider.asBinder();
3373 synchronized(mProviderMap) {
3374 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3375 if(prc == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003376 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldnt be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 return false;
3378 } else {
3379 prc.count--;
3380 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003381 // Schedule the actual remove asynchronously, since we
3382 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003383 // TODO: it would be nice to post a delayed message, so
3384 // if we come back and need the same provider quickly
3385 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003386 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3387 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 } //end if
3389 } //end else
3390 } //end synchronized
3391 return true;
3392 }
3393
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003394 final void completeRemoveProvider(IContentProvider provider) {
3395 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003396 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003397 synchronized(mProviderMap) {
3398 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3399 if(prc != null && prc.count == 0) {
3400 mProviderRefCountMap.remove(jBinder);
3401 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003402 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003403 }
3404 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003405
3406 if (name != null) {
3407 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003408 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003409 "ActivityManagerNative.removeContentProvider(" + name);
3410 ActivityManagerNative.getDefault().removeContentProvider(
3411 getApplicationThread(), name);
3412 } catch (RemoteException e) {
3413 //do nothing content provider object is dead any way
3414 } //end catch
3415 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003416 }
3417
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003418 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003420 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 }
3422 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003424 String name = null;
3425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003427 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003429 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 IBinder myBinder = pr.mProvider.asBinder();
3431 if (myBinder == providerBinder) {
3432 //find if its published by this process itself
3433 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003434 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003435 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003437 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 "death recipient");
3439 //content provider is in another process
3440 myBinder.unlinkToDeath(pr, 0);
3441 iter.remove();
3442 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003443 if(name == null) {
3444 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 }
3446 } //end if myBinder
3447 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003448
3449 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 }
3451
3452 final void removeDeadProvider(String name, IContentProvider provider) {
3453 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003454 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003456 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003457 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003458 if (removed != null) {
3459 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 }
3462 }
3463 }
3464
3465 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003466 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003468 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003469 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003470 if (removed != null) {
3471 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 }
3474 }
3475
3476 private final IContentProvider installProvider(Context context,
3477 IContentProvider provider, ProviderInfo info, boolean noisy) {
3478 ContentProvider localProvider = null;
3479 if (provider == null) {
3480 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003481 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 + info.name);
3483 }
3484 Context c = null;
3485 ApplicationInfo ai = info.applicationInfo;
3486 if (context.getPackageName().equals(ai.packageName)) {
3487 c = context;
3488 } else if (mInitialApplication != null &&
3489 mInitialApplication.getPackageName().equals(ai.packageName)) {
3490 c = mInitialApplication;
3491 } else {
3492 try {
3493 c = context.createPackageContext(ai.packageName,
3494 Context.CONTEXT_INCLUDE_CODE);
3495 } catch (PackageManager.NameNotFoundException e) {
3496 }
3497 }
3498 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003499 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 ai.packageName +
3501 " while loading content provider " +
3502 info.name);
3503 return null;
3504 }
3505 try {
3506 final java.lang.ClassLoader cl = c.getClassLoader();
3507 localProvider = (ContentProvider)cl.
3508 loadClass(info.name).newInstance();
3509 provider = localProvider.getIContentProvider();
3510 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003511 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 info.name + " from sourceDir " +
3513 info.applicationInfo.sourceDir);
3514 return null;
3515 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003516 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 TAG, "Instantiating local provider " + info.name);
3518 // XXX Need to create the correct context for this provider.
3519 localProvider.attachInfo(c, info);
3520 } catch (java.lang.Exception e) {
3521 if (!mInstrumentation.onException(null, e)) {
3522 throw new RuntimeException(
3523 "Unable to get provider " + info.name
3524 + ": " + e.toString(), e);
3525 }
3526 return null;
3527 }
3528 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003529 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 + info.name);
3531 }
3532
3533 synchronized (mProviderMap) {
3534 // Cache the pointer for the remote provider.
3535 String names[] = PATTERN_SEMICOLON.split(info.authority);
3536 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003537 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 localProvider);
3539 try {
3540 provider.asBinder().linkToDeath(pr, 0);
3541 mProviderMap.put(names[i], pr);
3542 } catch (RemoteException e) {
3543 return null;
3544 }
3545 }
3546 if (localProvider != null) {
3547 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003548 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 }
3550 }
3551
3552 return provider;
3553 }
3554
3555 private final void attach(boolean system) {
3556 sThreadLocal.set(this);
3557 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003559 ViewRoot.addFirstDrawHandler(new Runnable() {
3560 public void run() {
3561 ensureJitEnabled();
3562 }
3563 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3565 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3566 IActivityManager mgr = ActivityManagerNative.getDefault();
3567 try {
3568 mgr.attachApplication(mAppThread);
3569 } catch (RemoteException ex) {
3570 }
3571 } else {
3572 // Don't set application object here -- if the system crashes,
3573 // we can't display an alert, we just want to die die die.
3574 android.ddm.DdmHandleAppName.setAppName("system_process");
3575 try {
3576 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003577 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 context.init(getSystemContext().mPackageInfo, null, this);
3579 Application app = Instrumentation.newApplication(Application.class, context);
3580 mAllApplications.add(app);
3581 mInitialApplication = app;
3582 app.onCreate();
3583 } catch (Exception e) {
3584 throw new RuntimeException(
3585 "Unable to instantiate Application():" + e.toString(), e);
3586 }
3587 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003588
3589 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3590 public void onConfigurationChanged(Configuration newConfig) {
3591 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003592 // We need to apply this change to the resources
3593 // immediately, because upon returning the view
3594 // hierarchy will be informed about it.
3595 if (applyConfigurationToResourcesLocked(newConfig)) {
3596 // This actually changed the resources! Tell
3597 // everyone about it.
3598 if (mPendingConfiguration == null ||
3599 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3600 mPendingConfiguration = newConfig;
3601
3602 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3603 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003604 }
3605 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003606 }
3607 public void onLowMemory() {
3608 }
3609 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 }
3611
3612 private final void detach()
3613 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 sThreadLocal.set(null);
3615 }
3616
3617 public static final ActivityThread systemMain() {
3618 ActivityThread thread = new ActivityThread();
3619 thread.attach(true);
3620 return thread;
3621 }
3622
3623 public final void installSystemProviders(List providers) {
3624 if (providers != null) {
3625 installContentProviders(mInitialApplication,
3626 (List<ProviderInfo>)providers);
3627 }
3628 }
3629
3630 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003631 SamplingProfilerIntegration.start();
3632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 Process.setArgV0("<pre-initialized>");
3634
3635 Looper.prepareMainLooper();
3636
3637 ActivityThread thread = new ActivityThread();
3638 thread.attach(false);
3639
3640 Looper.loop();
3641
3642 if (Process.supportsProcesses()) {
3643 throw new RuntimeException("Main thread loop unexpectedly exited");
3644 }
3645
3646 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003647 String name = (thread.mInitialApplication != null)
3648 ? thread.mInitialApplication.getPackageName()
3649 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003650 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 }
3652}