blob: d83fce7b23f589a9ffecd82874ae84dd6c91244c [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;
Romain Guy52339202010-09-03 16:04:46 -070066import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.View;
68import android.view.ViewDebug;
69import android.view.ViewManager;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080070import android.view.ViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.view.Window;
72import android.view.WindowManager;
73import android.view.WindowManagerImpl;
74
75import com.android.internal.os.BinderInternal;
76import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070077import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
Romain Guya14c8e02010-09-03 16:51:54 -070079import dalvik.system.VMDebug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
81
82import java.io.File;
83import java.io.FileDescriptor;
84import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070085import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import java.io.PrintWriter;
87import java.lang.ref.WeakReference;
88import java.util.ArrayList;
89import java.util.HashMap;
90import java.util.Iterator;
91import java.util.List;
92import java.util.Locale;
93import java.util.Map;
94import java.util.TimeZone;
95import java.util.regex.Pattern;
96
Bob Leee5408332009-09-04 18:31:17 -070097import dalvik.system.SamplingProfiler;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099final class SuperNotCalledException extends AndroidRuntimeException {
100 public SuperNotCalledException(String msg) {
101 super(msg);
102 }
103}
104
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700105final class RemoteServiceException extends AndroidRuntimeException {
106 public RemoteServiceException(String msg) {
107 super(msg);
108 }
109}
110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111/**
112 * This manages the execution of the main thread in an
113 * application process, scheduling and executing activities,
114 * broadcasts, and other operations on it as the activity
115 * manager requests.
116 *
117 * {@hide}
118 */
119public final class ActivityThread {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700120 static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700121 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700123 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
124 static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700125 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700126 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700127 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
129 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
130 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
131 private static final int LOG_ON_PAUSE_CALLED = 30021;
132 private static final int LOG_ON_RESUME_CALLED = 30022;
133
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700134 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700135
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700136 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700138 final ApplicationThread mAppThread = new ApplicationThread();
139 final Looper mLooper = Looper.myLooper();
140 final H mH = new H();
141 final HashMap<IBinder, ActivityClientRecord> mActivities
142 = new HashMap<IBinder, ActivityClientRecord>();
143 // List of new activities (via ActivityRecord.nextIdle) that should
144 // be reported when next we idle.
145 ActivityClientRecord mNewActivities = null;
146 // Number of activities that are currently visible on-screen.
147 int mNumVisibleActivities = 0;
148 final HashMap<IBinder, Service> mServices
149 = new HashMap<IBinder, Service>();
150 AppBindData mBoundApplication;
151 Configuration mConfiguration;
152 Configuration mResConfiguration;
153 Application mInitialApplication;
154 final ArrayList<Application> mAllApplications
155 = new ArrayList<Application>();
156 // set of instantiated backup agents, keyed by package name
157 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700158 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700159 Instrumentation mInstrumentation;
160 String mInstrumentationAppDir = null;
161 String mInstrumentationAppPackage = null;
162 String mInstrumentedAppDir = null;
163 boolean mSystemThread = false;
164 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700166 // These can be accessed by multiple threads; mPackages is the lock.
167 // XXX For now we keep around information about all packages we have
168 // seen, not removing entries from this map.
169 final HashMap<String, WeakReference<LoadedApk>> mPackages
170 = new HashMap<String, WeakReference<LoadedApk>>();
171 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
172 = new HashMap<String, WeakReference<LoadedApk>>();
173 Display mDisplay = null;
174 DisplayMetrics mDisplayMetrics = null;
175 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
176 = new HashMap<ResourcesKey, WeakReference<Resources> >();
177 final ArrayList<ActivityClientRecord> mRelaunchingActivities
178 = new ArrayList<ActivityClientRecord>();
179 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700181 // The lock of mProviderMap protects the following variables.
182 final HashMap<String, ProviderClientRecord> mProviderMap
183 = new HashMap<String, ProviderClientRecord>();
184 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
185 = new HashMap<IBinder, ProviderRefCount>();
186 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
187 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700189 final GcIdler mGcIdler = new GcIdler();
190 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700192 static Handler sMainThreadHandler; // set once in main()
193
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700194 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700196 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 Intent intent;
198 Bundle state;
199 Activity activity;
200 Window window;
201 Activity parent;
202 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700203 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 boolean paused;
205 boolean stopped;
206 boolean hideForNow;
207 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700208 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700209 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700212 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
214 List<ResultInfo> pendingResults;
215 List<Intent> pendingIntents;
216
217 boolean startsNotResumed;
218 boolean isForward;
219
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700220 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 parent = null;
222 embeddedID = null;
223 paused = false;
224 stopped = false;
225 hideForNow = false;
226 nextIdle = null;
227 }
228
229 public String toString() {
230 ComponentName componentName = intent.getComponent();
231 return "ActivityRecord{"
232 + Integer.toHexString(System.identityHashCode(this))
233 + " token=" + token + " " + (componentName == null
234 ? "no component name" : componentName.toShortString())
235 + "}";
236 }
237 }
238
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700239 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 final String mName;
241 final IContentProvider mProvider;
242 final ContentProvider mLocalProvider;
243
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700244 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 ContentProvider localProvider) {
246 mName = name;
247 mProvider = provider;
248 mLocalProvider = localProvider;
249 }
250
251 public void binderDied() {
252 removeDeadProvider(mName, mProvider);
253 }
254 }
255
256 private static final class NewIntentData {
257 List<Intent> intents;
258 IBinder token;
259 public String toString() {
260 return "NewIntentData{intents=" + intents + " token=" + token + "}";
261 }
262 }
263
264 private static final class ReceiverData {
265 Intent intent;
266 ActivityInfo info;
267 int resultCode;
268 String resultData;
269 Bundle resultExtras;
270 boolean sync;
271 boolean resultAbort;
272 public String toString() {
273 return "ReceiverData{intent=" + intent + " packageName=" +
274 info.packageName + " resultCode=" + resultCode
275 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
276 }
277 }
278
Christopher Tate181fafa2009-05-14 11:12:14 -0700279 private static final class CreateBackupAgentData {
280 ApplicationInfo appInfo;
281 int backupMode;
282 public String toString() {
283 return "CreateBackupAgentData{appInfo=" + appInfo
284 + " backupAgent=" + appInfo.backupAgentName
285 + " mode=" + backupMode + "}";
286 }
287 }
Bob Leee5408332009-09-04 18:31:17 -0700288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 private static final class CreateServiceData {
290 IBinder token;
291 ServiceInfo info;
292 Intent intent;
293 public String toString() {
294 return "CreateServiceData{token=" + token + " className="
295 + info.name + " packageName=" + info.packageName
296 + " intent=" + intent + "}";
297 }
298 }
299
300 private static final class BindServiceData {
301 IBinder token;
302 Intent intent;
303 boolean rebind;
304 public String toString() {
305 return "BindServiceData{token=" + token + " intent=" + intent + "}";
306 }
307 }
308
309 private static final class ServiceArgsData {
310 IBinder token;
311 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700312 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 Intent args;
314 public String toString() {
315 return "ServiceArgsData{token=" + token + " startId=" + startId
316 + " args=" + args + "}";
317 }
318 }
319
320 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700321 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 String processName;
323 ApplicationInfo appInfo;
324 List<ProviderInfo> providers;
325 ComponentName instrumentationName;
326 String profileFile;
327 Bundle instrumentationArgs;
328 IInstrumentationWatcher instrumentationWatcher;
329 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700330 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 Configuration config;
332 boolean handlingProfiling;
333 public String toString() {
334 return "AppBindData{appInfo=" + appInfo + "}";
335 }
336 }
337
338 private static final class DumpServiceInfo {
339 FileDescriptor fd;
340 IBinder service;
341 String[] args;
342 boolean dumped;
343 }
344
345 private static final class ResultData {
346 IBinder token;
347 List<ResultInfo> results;
348 public String toString() {
349 return "ResultData{token=" + token + " results" + results + "}";
350 }
351 }
352
353 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800354 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 String what;
356 String who;
357 }
358
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700359 private static final class ProfilerControlData {
360 String path;
361 ParcelFileDescriptor fd;
362 }
363
Andy McFadden824c5102010-07-09 16:26:57 -0700364 private static final class DumpHeapData {
365 String path;
366 ParcelFileDescriptor fd;
367 }
368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 private final class ApplicationThread extends ApplicationThreadNative {
370 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
371 private static final String ONE_COUNT_COLUMN = "%17s %8d";
372 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700373 private static final String TWO_COUNT_COLUMNS_DB = "%20s %8d %20s %8d";
374 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 // Formatting for checkin service - update version if row format changes
377 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 public final void schedulePauseActivity(IBinder token, boolean finished,
380 boolean userLeaving, int configChanges) {
381 queueOrSendMessage(
382 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
383 token,
384 (userLeaving ? 1 : 0),
385 configChanges);
386 }
387
388 public final void scheduleStopActivity(IBinder token, boolean showWindow,
389 int configChanges) {
390 queueOrSendMessage(
391 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
392 token, 0, configChanges);
393 }
394
395 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
396 queueOrSendMessage(
397 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
398 token);
399 }
400
401 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
402 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
403 }
404
405 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
406 ResultData res = new ResultData();
407 res.token = token;
408 res.results = results;
409 queueOrSendMessage(H.SEND_RESULT, res);
410 }
411
412 // we use token to identify this activity without having to send the
413 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700414 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
416 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700417 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418
419 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700420 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 r.intent = intent;
422 r.activityInfo = info;
423 r.state = state;
424
425 r.pendingResults = pendingResults;
426 r.pendingIntents = pendingNewIntents;
427
428 r.startsNotResumed = notResumed;
429 r.isForward = isForward;
430
431 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
432 }
433
434 public final void scheduleRelaunchActivity(IBinder token,
435 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800436 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700437 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438
439 r.token = token;
440 r.pendingResults = pendingResults;
441 r.pendingIntents = pendingNewIntents;
442 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800443 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800445 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 mRelaunchingActivities.add(r);
447 }
Bob Leee5408332009-09-04 18:31:17 -0700448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
450 }
451
452 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
453 NewIntentData data = new NewIntentData();
454 data.intents = intents;
455 data.token = token;
456
457 queueOrSendMessage(H.NEW_INTENT, data);
458 }
459
460 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
461 int configChanges) {
462 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
463 configChanges);
464 }
465
466 public final void scheduleReceiver(Intent intent, ActivityInfo info,
467 int resultCode, String data, Bundle extras, boolean sync) {
468 ReceiverData r = new ReceiverData();
469
470 r.intent = intent;
471 r.info = info;
472 r.resultCode = resultCode;
473 r.resultData = data;
474 r.resultExtras = extras;
475 r.sync = sync;
476
477 queueOrSendMessage(H.RECEIVER, r);
478 }
479
Christopher Tate181fafa2009-05-14 11:12:14 -0700480 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
481 CreateBackupAgentData d = new CreateBackupAgentData();
482 d.appInfo = app;
483 d.backupMode = backupMode;
484
485 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
486 }
487
488 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
489 CreateBackupAgentData d = new CreateBackupAgentData();
490 d.appInfo = app;
491
492 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
493 }
494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 public final void scheduleCreateService(IBinder token,
496 ServiceInfo info) {
497 CreateServiceData s = new CreateServiceData();
498 s.token = token;
499 s.info = info;
500
501 queueOrSendMessage(H.CREATE_SERVICE, s);
502 }
503
504 public final void scheduleBindService(IBinder token, Intent intent,
505 boolean rebind) {
506 BindServiceData s = new BindServiceData();
507 s.token = token;
508 s.intent = intent;
509 s.rebind = rebind;
510
511 queueOrSendMessage(H.BIND_SERVICE, s);
512 }
513
514 public final void scheduleUnbindService(IBinder token, Intent intent) {
515 BindServiceData s = new BindServiceData();
516 s.token = token;
517 s.intent = intent;
518
519 queueOrSendMessage(H.UNBIND_SERVICE, s);
520 }
521
522 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700523 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 ServiceArgsData s = new ServiceArgsData();
525 s.token = token;
526 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700527 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 s.args = args;
529
530 queueOrSendMessage(H.SERVICE_ARGS, s);
531 }
532
533 public final void scheduleStopService(IBinder token) {
534 queueOrSendMessage(H.STOP_SERVICE, token);
535 }
536
537 public final void bindApplication(String processName,
538 ApplicationInfo appInfo, List<ProviderInfo> providers,
539 ComponentName instrumentationName, String profileFile,
540 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700541 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543
544 if (services != null) {
545 // Setup the service cache in the ServiceManager
546 ServiceManager.initServiceCache(services);
547 }
548
549 AppBindData data = new AppBindData();
550 data.processName = processName;
551 data.appInfo = appInfo;
552 data.providers = providers;
553 data.instrumentationName = instrumentationName;
554 data.profileFile = profileFile;
555 data.instrumentationArgs = instrumentationArgs;
556 data.instrumentationWatcher = instrumentationWatcher;
557 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700558 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 data.config = config;
560 queueOrSendMessage(H.BIND_APPLICATION, data);
561 }
562
563 public final void scheduleExit() {
564 queueOrSendMessage(H.EXIT_APPLICATION, null);
565 }
566
Christopher Tate5e1ab332009-09-01 20:32:49 -0700567 public final void scheduleSuicide() {
568 queueOrSendMessage(H.SUICIDE, null);
569 }
570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 public void requestThumbnail(IBinder token) {
572 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
573 }
574
575 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800576 synchronized (mPackages) {
577 if (mPendingConfiguration == null ||
578 mPendingConfiguration.isOtherSeqNewer(config)) {
579 mPendingConfiguration = config;
580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 }
582 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
583 }
584
585 public void updateTimeZone() {
586 TimeZone.setDefault(null);
587 }
588
589 public void processInBackground() {
590 mH.removeMessages(H.GC_WHEN_IDLE);
591 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
592 }
593
594 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
595 DumpServiceInfo data = new DumpServiceInfo();
596 data.fd = fd;
597 data.service = servicetoken;
598 data.args = args;
599 data.dumped = false;
600 queueOrSendMessage(H.DUMP_SERVICE, data);
601 synchronized (data) {
602 while (!data.dumped) {
603 try {
604 data.wait();
605 } catch (InterruptedException e) {
606 // no need to do anything here, we will keep waiting until
607 // dumped is set
608 }
609 }
610 }
611 }
612
613 // This function exists to make sure all receiver dispatching is
614 // correctly ordered, since these are one-way calls and the binder driver
615 // applies transaction ordering per object for such calls.
616 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700617 int resultCode, String dataStr, Bundle extras, boolean ordered,
618 boolean sticky) throws RemoteException {
619 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 }
Bob Leee5408332009-09-04 18:31:17 -0700621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 public void scheduleLowMemory() {
623 queueOrSendMessage(H.LOW_MEMORY, null);
624 }
625
626 public void scheduleActivityConfigurationChanged(IBinder token) {
627 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
628 }
629
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700630 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
631 ProfilerControlData pcd = new ProfilerControlData();
632 pcd.path = path;
633 pcd.fd = fd;
634 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800635 }
636
Andy McFadden824c5102010-07-09 16:26:57 -0700637 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
638 DumpHeapData dhd = new DumpHeapData();
639 dhd.path = path;
640 dhd.fd = fd;
641 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
642 }
643
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700644 public void setSchedulingGroup(int group) {
645 // Note: do this immediately, since going into the foreground
646 // should happen regardless of what pending work we have to do
647 // and the activity manager will wait for us to report back that
648 // we are done before sending us to the background.
649 try {
650 Process.setProcessGroup(Process.myPid(), group);
651 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800652 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700653 }
654 }
Bob Leee5408332009-09-04 18:31:17 -0700655
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700656 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
657 Debug.getMemoryInfo(outInfo);
658 }
Bob Leee5408332009-09-04 18:31:17 -0700659
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700660 public void dispatchPackageBroadcast(int cmd, String[] packages) {
661 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
662 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700663
664 public void scheduleCrash(String msg) {
665 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
666 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 @Override
669 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
670 long nativeMax = Debug.getNativeHeapSize() / 1024;
671 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
672 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
673
674 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
675 Debug.getMemoryInfo(memInfo);
676
677 final int nativeShared = memInfo.nativeSharedDirty;
678 final int dalvikShared = memInfo.dalvikSharedDirty;
679 final int otherShared = memInfo.otherSharedDirty;
680
681 final int nativePrivate = memInfo.nativePrivateDirty;
682 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
683 final int otherPrivate = memInfo.otherPrivateDirty;
684
685 Runtime runtime = Runtime.getRuntime();
686
687 long dalvikMax = runtime.totalMemory() / 1024;
688 long dalvikFree = runtime.freeMemory() / 1024;
689 long dalvikAllocated = dalvikMax - dalvikFree;
690 long viewInstanceCount = ViewDebug.getViewInstanceCount();
691 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Romain Guya14c8e02010-09-03 16:51:54 -0700692 long appContextInstanceCount = VMDebug.countInstancesOfClass(ContextImpl.class);
693 long activityInstanceCount = VMDebug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 int globalAssetCount = AssetManager.getGlobalAssetCount();
695 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
696 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
697 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
698 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
699 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
700 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800701 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 // Check to see if we were called by checkin server. If so, print terse format.
704 boolean doCheckinFormat = false;
705 if (args != null) {
706 for (String arg : args) {
707 if ("-c".equals(arg)) doCheckinFormat = true;
708 }
709 }
Bob Leee5408332009-09-04 18:31:17 -0700710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 // For checkin, we print one long comma-separated list of values
712 if (doCheckinFormat) {
713 // NOTE: if you change anything significant below, also consider changing
714 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700715 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 // Header
719 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
720 pw.print(Process.myPid()); pw.print(',');
721 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 // Heap info - max
724 pw.print(nativeMax); pw.print(',');
725 pw.print(dalvikMax); pw.print(',');
726 pw.print("N/A,");
727 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 // Heap info - allocated
730 pw.print(nativeAllocated); pw.print(',');
731 pw.print(dalvikAllocated); pw.print(',');
732 pw.print("N/A,");
733 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 // Heap info - free
736 pw.print(nativeFree); pw.print(',');
737 pw.print(dalvikFree); pw.print(',');
738 pw.print("N/A,");
739 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 // Heap info - proportional set size
742 pw.print(memInfo.nativePss); pw.print(',');
743 pw.print(memInfo.dalvikPss); pw.print(',');
744 pw.print(memInfo.otherPss); pw.print(',');
745 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700748 pw.print(nativeShared); pw.print(',');
749 pw.print(dalvikShared); pw.print(',');
750 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700754 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 pw.print(dalvikPrivate); pw.print(',');
756 pw.print(otherPrivate); pw.print(',');
757 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 // Object counts
760 pw.print(viewInstanceCount); pw.print(',');
761 pw.print(viewRootInstanceCount); pw.print(',');
762 pw.print(appContextInstanceCount); pw.print(',');
763 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 pw.print(globalAssetCount); pw.print(',');
766 pw.print(globalAssetManagerCount); pw.print(',');
767 pw.print(binderLocalObjectCount); pw.print(',');
768 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 pw.print(binderDeathObjectCount); pw.print(',');
771 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 // SQL
774 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800775 pw.print(stats.memoryUsed / 1024); pw.print(',');
776 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
777 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
778 for (int i = 0; i < stats.dbStats.size(); i++) {
779 DbStats dbStats = stats.dbStats.get(i);
780 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700781 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800782 pw.print(',');
783 }
Bob Leee5408332009-09-04 18:31:17 -0700784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 return;
786 }
Bob Leee5408332009-09-04 18:31:17 -0700787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 // otherwise, show human-readable format
789 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
790 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
791 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
792 nativeAllocated + dalvikAllocated);
793 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
794 nativeFree + dalvikFree);
795
796 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
797 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
798
799 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
800 nativeShared + dalvikShared + otherShared);
801 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
802 nativePrivate + dalvikPrivate + otherPrivate);
803
804 pw.println(" ");
805 pw.println(" Objects");
806 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
807 viewRootInstanceCount);
808
809 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
810 "Activities:", activityInstanceCount);
811
812 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
813 "AssetManagers:", globalAssetManagerCount);
814
815 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
816 "Proxy Binders:", binderProxyObjectCount);
817 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
818
819 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 // SQLite mem info
822 pw.println(" ");
823 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700824 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800825 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700826 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
827 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800828 pw.println(" ");
829 int N = stats.dbStats.size();
830 if (N > 0) {
831 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700832 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
833 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800834 for (int i = 0; i < N; i++) {
835 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700836 printRow(pw, DB_INFO_FORMAT,
837 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
838 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
839 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
840 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800841 }
842 }
Bob Leee5408332009-09-04 18:31:17 -0700843
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700844 // Asset details.
845 String assetAlloc = AssetManager.getAssetAllocations();
846 if (assetAlloc != null) {
847 pw.println(" ");
848 pw.println(" Asset Allocations");
849 pw.print(assetAlloc);
850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
852
853 private void printRow(PrintWriter pw, String format, Object...objs) {
854 pw.println(String.format(format, objs));
855 }
856 }
857
858 private final class H extends Handler {
859 public static final int LAUNCH_ACTIVITY = 100;
860 public static final int PAUSE_ACTIVITY = 101;
861 public static final int PAUSE_ACTIVITY_FINISHING= 102;
862 public static final int STOP_ACTIVITY_SHOW = 103;
863 public static final int STOP_ACTIVITY_HIDE = 104;
864 public static final int SHOW_WINDOW = 105;
865 public static final int HIDE_WINDOW = 106;
866 public static final int RESUME_ACTIVITY = 107;
867 public static final int SEND_RESULT = 108;
868 public static final int DESTROY_ACTIVITY = 109;
869 public static final int BIND_APPLICATION = 110;
870 public static final int EXIT_APPLICATION = 111;
871 public static final int NEW_INTENT = 112;
872 public static final int RECEIVER = 113;
873 public static final int CREATE_SERVICE = 114;
874 public static final int SERVICE_ARGS = 115;
875 public static final int STOP_SERVICE = 116;
876 public static final int REQUEST_THUMBNAIL = 117;
877 public static final int CONFIGURATION_CHANGED = 118;
878 public static final int CLEAN_UP_CONTEXT = 119;
879 public static final int GC_WHEN_IDLE = 120;
880 public static final int BIND_SERVICE = 121;
881 public static final int UNBIND_SERVICE = 122;
882 public static final int DUMP_SERVICE = 123;
883 public static final int LOW_MEMORY = 124;
884 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
885 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800886 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700887 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700888 public static final int DESTROY_BACKUP_AGENT = 129;
889 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700890 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800891 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700892 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700893 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700894 public static final int DUMP_HEAP = 135;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 String codeToString(int code) {
896 if (localLOGV) {
897 switch (code) {
898 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
899 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
900 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
901 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
902 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
903 case SHOW_WINDOW: return "SHOW_WINDOW";
904 case HIDE_WINDOW: return "HIDE_WINDOW";
905 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
906 case SEND_RESULT: return "SEND_RESULT";
907 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
908 case BIND_APPLICATION: return "BIND_APPLICATION";
909 case EXIT_APPLICATION: return "EXIT_APPLICATION";
910 case NEW_INTENT: return "NEW_INTENT";
911 case RECEIVER: return "RECEIVER";
912 case CREATE_SERVICE: return "CREATE_SERVICE";
913 case SERVICE_ARGS: return "SERVICE_ARGS";
914 case STOP_SERVICE: return "STOP_SERVICE";
915 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
916 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
917 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
918 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
919 case BIND_SERVICE: return "BIND_SERVICE";
920 case UNBIND_SERVICE: return "UNBIND_SERVICE";
921 case DUMP_SERVICE: return "DUMP_SERVICE";
922 case LOW_MEMORY: return "LOW_MEMORY";
923 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
924 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800925 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700926 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
927 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700928 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700929 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800930 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700931 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700932 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -0700933 case DUMP_HEAP: return "DUMP_HEAP";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
935 }
936 return "(unknown)";
937 }
938 public void handleMessage(Message msg) {
939 switch (msg.what) {
940 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700941 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942
943 r.packageInfo = getPackageInfoNoCheck(
944 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700945 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 } break;
947 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700948 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 handleRelaunchActivity(r, msg.arg1);
950 } break;
951 case PAUSE_ACTIVITY:
952 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700953 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 break;
955 case PAUSE_ACTIVITY_FINISHING:
956 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
957 break;
958 case STOP_ACTIVITY_SHOW:
959 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
960 break;
961 case STOP_ACTIVITY_HIDE:
962 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
963 break;
964 case SHOW_WINDOW:
965 handleWindowVisibility((IBinder)msg.obj, true);
966 break;
967 case HIDE_WINDOW:
968 handleWindowVisibility((IBinder)msg.obj, false);
969 break;
970 case RESUME_ACTIVITY:
971 handleResumeActivity((IBinder)msg.obj, true,
972 msg.arg1 != 0);
973 break;
974 case SEND_RESULT:
975 handleSendResult((ResultData)msg.obj);
976 break;
977 case DESTROY_ACTIVITY:
978 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
979 msg.arg2, false);
980 break;
981 case BIND_APPLICATION:
982 AppBindData data = (AppBindData)msg.obj;
983 handleBindApplication(data);
984 break;
985 case EXIT_APPLICATION:
986 if (mInitialApplication != null) {
987 mInitialApplication.onTerminate();
988 }
989 Looper.myLooper().quit();
990 break;
991 case NEW_INTENT:
992 handleNewIntent((NewIntentData)msg.obj);
993 break;
994 case RECEIVER:
995 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700996 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 break;
998 case CREATE_SERVICE:
999 handleCreateService((CreateServiceData)msg.obj);
1000 break;
1001 case BIND_SERVICE:
1002 handleBindService((BindServiceData)msg.obj);
1003 break;
1004 case UNBIND_SERVICE:
1005 handleUnbindService((BindServiceData)msg.obj);
1006 break;
1007 case SERVICE_ARGS:
1008 handleServiceArgs((ServiceArgsData)msg.obj);
1009 break;
1010 case STOP_SERVICE:
1011 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001012 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 break;
1014 case REQUEST_THUMBNAIL:
1015 handleRequestThumbnail((IBinder)msg.obj);
1016 break;
1017 case CONFIGURATION_CHANGED:
1018 handleConfigurationChanged((Configuration)msg.obj);
1019 break;
1020 case CLEAN_UP_CONTEXT:
1021 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1022 cci.context.performFinalCleanup(cci.who, cci.what);
1023 break;
1024 case GC_WHEN_IDLE:
1025 scheduleGcIdler();
1026 break;
1027 case DUMP_SERVICE:
1028 handleDumpService((DumpServiceInfo)msg.obj);
1029 break;
1030 case LOW_MEMORY:
1031 handleLowMemory();
1032 break;
1033 case ACTIVITY_CONFIGURATION_CHANGED:
1034 handleActivityConfigurationChanged((IBinder)msg.obj);
1035 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001036 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001037 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001038 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001039 case CREATE_BACKUP_AGENT:
1040 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1041 break;
1042 case DESTROY_BACKUP_AGENT:
1043 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1044 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001045 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001046 Process.killProcess(Process.myPid());
1047 break;
1048 case REMOVE_PROVIDER:
1049 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001050 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001051 case ENABLE_JIT:
1052 ensureJitEnabled();
1053 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001054 case DISPATCH_PACKAGE_BROADCAST:
1055 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1056 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001057 case SCHEDULE_CRASH:
1058 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001059 case DUMP_HEAP:
1060 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1061 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 }
1063 }
Bob Leee5408332009-09-04 18:31:17 -07001064
1065 void maybeSnapshot() {
1066 if (mBoundApplication != null) {
Sen Hubde75702010-05-28 01:54:03 -07001067 // convert the *private* ActivityThread.PackageInfo to *public* known
1068 // android.content.pm.PackageInfo
1069 String packageName = mBoundApplication.info.mPackageName;
1070 android.content.pm.PackageInfo packageInfo = null;
1071 try {
1072 Context context = getSystemContext();
1073 if(context == null) {
1074 Log.e(TAG, "cannot get a valid context");
1075 return;
1076 }
1077 PackageManager pm = context.getPackageManager();
1078 if(pm == null) {
1079 Log.e(TAG, "cannot get a valid PackageManager");
1080 return;
1081 }
1082 packageInfo = pm.getPackageInfo(
1083 packageName, PackageManager.GET_ACTIVITIES);
1084 } catch (NameNotFoundException e) {
1085 Log.e(TAG, "cannot get package info for " + packageName, e);
1086 }
1087 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001088 }
1089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 }
1091
1092 private final class Idler implements MessageQueue.IdleHandler {
1093 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001094 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 if (a != null) {
1096 mNewActivities = null;
1097 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001098 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001100 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 TAG, "Reporting idle of " + a +
1102 " finished=" +
1103 (a.activity != null ? a.activity.mFinished : false));
1104 if (a.activity != null && !a.activity.mFinished) {
1105 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001106 am.activityIdle(a.token, a.createdConfig);
1107 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 } catch (RemoteException ex) {
1109 }
1110 }
1111 prev = a;
1112 a = a.nextIdle;
1113 prev.nextIdle = null;
1114 } while (a != null);
1115 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001116 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 return false;
1118 }
1119 }
1120
1121 final class GcIdler implements MessageQueue.IdleHandler {
1122 public final boolean queueIdle() {
1123 doGcIfNeeded();
1124 return false;
1125 }
1126 }
1127
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001128 private final static class ResourcesKey {
1129 final private String mResDir;
1130 final private float mScale;
1131 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001132
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001133 ResourcesKey(String resDir, float scale) {
1134 mResDir = resDir;
1135 mScale = scale;
1136 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1137 }
Bob Leee5408332009-09-04 18:31:17 -07001138
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001139 @Override
1140 public int hashCode() {
1141 return mHash;
1142 }
1143
1144 @Override
1145 public boolean equals(Object obj) {
1146 if (!(obj instanceof ResourcesKey)) {
1147 return false;
1148 }
1149 ResourcesKey peer = (ResourcesKey) obj;
1150 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1151 }
1152 }
1153
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001154 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001155 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001158 public static final String currentPackageName() {
1159 ActivityThread am = currentActivityThread();
1160 return (am != null && am.mBoundApplication != null)
1161 ? am.mBoundApplication.processName : null;
1162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001164 public static final Application currentApplication() {
1165 ActivityThread am = currentActivityThread();
1166 return am != null ? am.mInitialApplication : null;
1167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001169 public static IPackageManager getPackageManager() {
1170 if (sPackageManager != null) {
1171 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1172 return sPackageManager;
1173 }
1174 IBinder b = ServiceManager.getService("package");
1175 //Slog.v("PackageManager", "default service binder = " + b);
1176 sPackageManager = IPackageManager.Stub.asInterface(b);
1177 //Slog.v("PackageManager", "default service = " + sPackageManager);
1178 return sPackageManager;
1179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001181 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1182 if (mDisplayMetrics != null && !forceUpdate) {
1183 return mDisplayMetrics;
1184 }
1185 if (mDisplay == null) {
1186 WindowManager wm = WindowManagerImpl.getDefault();
1187 mDisplay = wm.getDefaultDisplay();
1188 }
1189 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1190 mDisplay.getMetrics(metrics);
1191 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1192 // + metrics.heightPixels + " den=" + metrics.density
1193 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1194 return metrics;
1195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001197 /**
1198 * Creates the top level Resources for applications with the given compatibility info.
1199 *
1200 * @param resDir the resource directory.
1201 * @param compInfo the compability info. It will use the default compatibility info when it's
1202 * null.
1203 */
1204 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1205 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1206 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001208 // Resources is app scale dependent.
1209 if (false) {
1210 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1211 + compInfo.applicationScale);
1212 }
1213 WeakReference<Resources> wr = mActiveResources.get(key);
1214 r = wr != null ? wr.get() : null;
1215 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1216 if (r != null && r.getAssets().isUpToDate()) {
1217 if (false) {
1218 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1219 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1220 }
1221 return r;
1222 }
1223 }
1224
1225 //if (r != null) {
1226 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1227 // + r + " " + resDir);
1228 //}
1229
1230 AssetManager assets = new AssetManager();
1231 if (assets.addAssetPath(resDir) == 0) {
1232 return null;
1233 }
1234
1235 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1236 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1237 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1238 if (false) {
1239 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1240 + r.getConfiguration() + " appScale="
1241 + r.getCompatibilityInfo().applicationScale);
1242 }
1243
1244 synchronized (mPackages) {
1245 WeakReference<Resources> wr = mActiveResources.get(key);
1246 Resources existing = wr != null ? wr.get() : null;
1247 if (existing != null && existing.getAssets().isUpToDate()) {
1248 // Someone else already created the resources while we were
1249 // unlocked; go ahead and use theirs.
1250 r.getAssets().close();
1251 return existing;
1252 }
1253
1254 // XXX need to remove entries when weak references go away
1255 mActiveResources.put(key, new WeakReference<Resources>(r));
1256 return r;
1257 }
1258 }
1259
1260 /**
1261 * Creates the top level resources for the given package.
1262 */
1263 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1264 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1265 }
1266
1267 final Handler getHandler() {
1268 return mH;
1269 }
1270
1271 public final LoadedApk getPackageInfo(String packageName, int flags) {
1272 synchronized (mPackages) {
1273 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1275 ref = mPackages.get(packageName);
1276 } else {
1277 ref = mResourcePackages.get(packageName);
1278 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001279 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001280 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001281 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1282 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 if (packageInfo != null && (packageInfo.mResources == null
1284 || packageInfo.mResources.getAssets().isUpToDate())) {
1285 if (packageInfo.isSecurityViolation()
1286 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1287 throw new SecurityException(
1288 "Requesting code from " + packageName
1289 + " to be run in process "
1290 + mBoundApplication.processName
1291 + "/" + mBoundApplication.appInfo.uid);
1292 }
1293 return packageInfo;
1294 }
1295 }
1296
1297 ApplicationInfo ai = null;
1298 try {
1299 ai = getPackageManager().getApplicationInfo(packageName,
1300 PackageManager.GET_SHARED_LIBRARY_FILES);
1301 } catch (RemoteException e) {
1302 }
1303
1304 if (ai != null) {
1305 return getPackageInfo(ai, flags);
1306 }
1307
1308 return null;
1309 }
1310
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001311 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1313 boolean securityViolation = includeCode && ai.uid != 0
1314 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1315 ? ai.uid != mBoundApplication.appInfo.uid : true);
1316 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1317 |Context.CONTEXT_IGNORE_SECURITY))
1318 == Context.CONTEXT_INCLUDE_CODE) {
1319 if (securityViolation) {
1320 String msg = "Requesting code from " + ai.packageName
1321 + " (with uid " + ai.uid + ")";
1322 if (mBoundApplication != null) {
1323 msg = msg + " to be run in process "
1324 + mBoundApplication.processName + " (with uid "
1325 + mBoundApplication.appInfo.uid + ")";
1326 }
1327 throw new SecurityException(msg);
1328 }
1329 }
1330 return getPackageInfo(ai, null, securityViolation, includeCode);
1331 }
1332
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001333 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 return getPackageInfo(ai, null, false, true);
1335 }
1336
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001337 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1339 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001340 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 if (includeCode) {
1342 ref = mPackages.get(aInfo.packageName);
1343 } else {
1344 ref = mResourcePackages.get(aInfo.packageName);
1345 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001346 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 if (packageInfo == null || (packageInfo.mResources != null
1348 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001349 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 : "Loading resource-only package ") + aInfo.packageName
1351 + " (in " + (mBoundApplication != null
1352 ? mBoundApplication.processName : null)
1353 + ")");
1354 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001355 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 securityViolation, includeCode &&
1357 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1358 if (includeCode) {
1359 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001360 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 } else {
1362 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001363 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
1365 }
1366 return packageInfo;
1367 }
1368 }
1369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 ActivityThread() {
1371 }
1372
1373 public ApplicationThread getApplicationThread()
1374 {
1375 return mAppThread;
1376 }
1377
1378 public Instrumentation getInstrumentation()
1379 {
1380 return mInstrumentation;
1381 }
1382
1383 public Configuration getConfiguration() {
1384 return mConfiguration;
1385 }
1386
1387 public boolean isProfiling() {
1388 return mBoundApplication != null && mBoundApplication.profileFile != null;
1389 }
1390
1391 public String getProfileFilePath() {
1392 return mBoundApplication.profileFile;
1393 }
1394
1395 public Looper getLooper() {
1396 return mLooper;
1397 }
1398
1399 public Application getApplication() {
1400 return mInitialApplication;
1401 }
Bob Leee5408332009-09-04 18:31:17 -07001402
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001403 public String getProcessName() {
1404 return mBoundApplication.processName;
1405 }
Bob Leee5408332009-09-04 18:31:17 -07001406
Dianne Hackborn21556372010-02-04 16:34:40 -08001407 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 synchronized (this) {
1409 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001410 ContextImpl context =
1411 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001412 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 context.init(info, null, this);
1414 context.getResources().updateConfiguration(
1415 getConfiguration(), getDisplayMetricsLocked(false));
1416 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001417 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 // + ": " + context.getResources().getConfiguration());
1419 }
1420 }
1421 return mSystemContext;
1422 }
1423
Mike Cleron432b7132009-09-24 15:28:29 -07001424 public void installSystemApplicationInfo(ApplicationInfo info) {
1425 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001426 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001427 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001428 }
1429 }
1430
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001431 void ensureJitEnabled() {
1432 if (!mJitEnabled) {
1433 mJitEnabled = true;
1434 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1435 }
1436 }
1437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 void scheduleGcIdler() {
1439 if (!mGcIdlerScheduled) {
1440 mGcIdlerScheduled = true;
1441 Looper.myQueue().addIdleHandler(mGcIdler);
1442 }
1443 mH.removeMessages(H.GC_WHEN_IDLE);
1444 }
1445
1446 void unscheduleGcIdler() {
1447 if (mGcIdlerScheduled) {
1448 mGcIdlerScheduled = false;
1449 Looper.myQueue().removeIdleHandler(mGcIdler);
1450 }
1451 mH.removeMessages(H.GC_WHEN_IDLE);
1452 }
1453
1454 void doGcIfNeeded() {
1455 mGcIdlerScheduled = false;
1456 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001457 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 // + "m now=" + now);
1459 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001460 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 BinderInternal.forceGc("bg");
1462 }
1463 }
1464
1465 public final ActivityInfo resolveActivityInfo(Intent intent) {
1466 ActivityInfo aInfo = intent.resolveActivityInfo(
1467 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1468 if (aInfo == null) {
1469 // Throw an exception.
1470 Instrumentation.checkStartActivityResult(
1471 IActivityManager.START_CLASS_NOT_FOUND, intent);
1472 }
1473 return aInfo;
1474 }
Bob Leee5408332009-09-04 18:31:17 -07001475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001478 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001479 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001481 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 r.intent = intent;
1483 r.state = state;
1484 r.parent = parent;
1485 r.embeddedID = id;
1486 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001487 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 if (localLOGV) {
1489 ComponentName compname = intent.getComponent();
1490 String name;
1491 if (compname != null) {
1492 name = compname.toShortString();
1493 } else {
1494 name = "(Intent " + intent + ").getComponent() returned null";
1495 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001496 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 + ", comp=" + name
1498 + ", token=" + token);
1499 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001500 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502
1503 public final Activity getActivity(IBinder token) {
1504 return mActivities.get(token).activity;
1505 }
1506
1507 public final void sendActivityResult(
1508 IBinder token, String id, int requestCode,
1509 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001510 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001511 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1513 list.add(new ResultInfo(id, requestCode, resultCode, data));
1514 mAppThread.scheduleSendResult(token, list);
1515 }
1516
1517 // if the thread hasn't started yet, we don't have the handler, so just
1518 // save the messages until we're ready.
1519 private final void queueOrSendMessage(int what, Object obj) {
1520 queueOrSendMessage(what, obj, 0, 0);
1521 }
1522
1523 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1524 queueOrSendMessage(what, obj, arg1, 0);
1525 }
1526
1527 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1528 synchronized (this) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001529 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1531 + ": " + arg1 + " / " + obj);
1532 Message msg = Message.obtain();
1533 msg.what = what;
1534 msg.obj = obj;
1535 msg.arg1 = arg1;
1536 msg.arg2 = arg2;
1537 mH.sendMessage(msg);
1538 }
1539 }
1540
Dianne Hackborn21556372010-02-04 16:34:40 -08001541 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 String what) {
1543 ContextCleanupInfo cci = new ContextCleanupInfo();
1544 cci.context = context;
1545 cci.who = who;
1546 cci.what = what;
1547 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1548 }
1549
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001550 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1552
1553 ActivityInfo aInfo = r.activityInfo;
1554 if (r.packageInfo == null) {
1555 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1556 Context.CONTEXT_INCLUDE_CODE);
1557 }
Bob Leee5408332009-09-04 18:31:17 -07001558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 ComponentName component = r.intent.getComponent();
1560 if (component == null) {
1561 component = r.intent.resolveActivity(
1562 mInitialApplication.getPackageManager());
1563 r.intent.setComponent(component);
1564 }
1565
1566 if (r.activityInfo.targetActivity != null) {
1567 component = new ComponentName(r.activityInfo.packageName,
1568 r.activityInfo.targetActivity);
1569 }
1570
1571 Activity activity = null;
1572 try {
1573 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1574 activity = mInstrumentation.newActivity(
1575 cl, component.getClassName(), r.intent);
1576 r.intent.setExtrasClassLoader(cl);
1577 if (r.state != null) {
1578 r.state.setClassLoader(cl);
1579 }
1580 } catch (Exception e) {
1581 if (!mInstrumentation.onException(activity, e)) {
1582 throw new RuntimeException(
1583 "Unable to instantiate activity " + component
1584 + ": " + e.toString(), e);
1585 }
1586 }
1587
1588 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001589 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001590
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001591 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1592 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 TAG, r + ": app=" + app
1594 + ", appName=" + app.getPackageName()
1595 + ", pkg=" + r.packageInfo.getPackageName()
1596 + ", comp=" + r.intent.getComponent().toShortString()
1597 + ", dir=" + r.packageInfo.getAppDir());
1598
1599 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001600 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 appContext.init(r.packageInfo, r.token, this);
1602 appContext.setOuterContext(activity);
1603 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1604 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001605 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001606 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001607 activity.attach(appContext, this, getInstrumentation(), r.token,
1608 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001609 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001610
Christopher Tateb70f3df2009-04-07 16:07:59 -07001611 if (customIntent != null) {
1612 activity.mIntent = customIntent;
1613 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001614 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 activity.mStartedActivity = false;
1616 int theme = r.activityInfo.getThemeResource();
1617 if (theme != 0) {
1618 activity.setTheme(theme);
1619 }
1620
1621 activity.mCalled = false;
1622 mInstrumentation.callActivityOnCreate(activity, r.state);
1623 if (!activity.mCalled) {
1624 throw new SuperNotCalledException(
1625 "Activity " + r.intent.getComponent().toShortString() +
1626 " did not call through to super.onCreate()");
1627 }
1628 r.activity = activity;
1629 r.stopped = true;
1630 if (!r.activity.mFinished) {
1631 activity.performStart();
1632 r.stopped = false;
1633 }
1634 if (!r.activity.mFinished) {
1635 if (r.state != null) {
1636 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1637 }
1638 }
1639 if (!r.activity.mFinished) {
1640 activity.mCalled = false;
1641 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1642 if (!activity.mCalled) {
1643 throw new SuperNotCalledException(
1644 "Activity " + r.intent.getComponent().toShortString() +
1645 " did not call through to super.onPostCreate()");
1646 }
1647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 r.paused = true;
1650
1651 mActivities.put(r.token, r);
1652
1653 } catch (SuperNotCalledException e) {
1654 throw e;
1655
1656 } catch (Exception e) {
1657 if (!mInstrumentation.onException(activity, e)) {
1658 throw new RuntimeException(
1659 "Unable to start activity " + component
1660 + ": " + e.toString(), e);
1661 }
1662 }
1663
1664 return activity;
1665 }
1666
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001667 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 // If we are getting ready to gc after going to the background, well
1669 // we are back active so skip it.
1670 unscheduleGcIdler();
1671
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001672 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001674 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675
1676 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001677 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001678 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 handleResumeActivity(r.token, false, r.isForward);
1680
1681 if (!r.activity.mFinished && r.startsNotResumed) {
1682 // The activity manager actually wants this one to start out
1683 // paused, because it needs to be visible but isn't in the
1684 // foreground. We accomplish this by going through the
1685 // normal startup (because activities expect to go through
1686 // onResume() the first time they run, before their window
1687 // is displayed), and then pausing it. However, in this case
1688 // we do -not- need to do the full pause cycle (of freezing
1689 // and such) because the activity manager assumes it can just
1690 // retain the current state it has.
1691 try {
1692 r.activity.mCalled = false;
1693 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001694 // We need to keep around the original state, in case
1695 // we need to be created again.
1696 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 if (!r.activity.mCalled) {
1698 throw new SuperNotCalledException(
1699 "Activity " + r.intent.getComponent().toShortString() +
1700 " did not call through to super.onPause()");
1701 }
1702
1703 } catch (SuperNotCalledException e) {
1704 throw e;
1705
1706 } catch (Exception e) {
1707 if (!mInstrumentation.onException(r.activity, e)) {
1708 throw new RuntimeException(
1709 "Unable to pause activity "
1710 + r.intent.getComponent().toShortString()
1711 + ": " + e.toString(), e);
1712 }
1713 }
1714 r.paused = true;
1715 }
1716 } else {
1717 // If there was an error, for any reason, tell the activity
1718 // manager to stop us.
1719 try {
1720 ActivityManagerNative.getDefault()
1721 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1722 } catch (RemoteException ex) {
1723 }
1724 }
1725 }
1726
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001727 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 List<Intent> intents) {
1729 final int N = intents.size();
1730 for (int i=0; i<N; i++) {
1731 Intent intent = intents.get(i);
1732 intent.setExtrasClassLoader(r.activity.getClassLoader());
1733 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1734 }
1735 }
1736
1737 public final void performNewIntents(IBinder token,
1738 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001739 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 if (r != null) {
1741 final boolean resumed = !r.paused;
1742 if (resumed) {
1743 mInstrumentation.callActivityOnPause(r.activity);
1744 }
1745 deliverNewIntents(r, intents);
1746 if (resumed) {
1747 mInstrumentation.callActivityOnResume(r.activity);
1748 }
1749 }
1750 }
Bob Leee5408332009-09-04 18:31:17 -07001751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 private final void handleNewIntent(NewIntentData data) {
1753 performNewIntents(data.token, data.intents);
1754 }
1755
1756 private final void handleReceiver(ReceiverData data) {
1757 // If we are getting ready to gc after going to the background, well
1758 // we are back active so skip it.
1759 unscheduleGcIdler();
1760
1761 String component = data.intent.getComponent().getClassName();
1762
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001763 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 data.info.applicationInfo);
1765
1766 IActivityManager mgr = ActivityManagerNative.getDefault();
1767
1768 BroadcastReceiver receiver = null;
1769 try {
1770 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1771 data.intent.setExtrasClassLoader(cl);
1772 if (data.resultExtras != null) {
1773 data.resultExtras.setClassLoader(cl);
1774 }
1775 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1776 } catch (Exception e) {
1777 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001778 if (DEBUG_BROADCAST) Slog.i(TAG,
1779 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1781 data.resultData, data.resultExtras, data.resultAbort);
1782 } catch (RemoteException ex) {
1783 }
1784 throw new RuntimeException(
1785 "Unable to instantiate receiver " + component
1786 + ": " + e.toString(), e);
1787 }
1788
1789 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001790 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001791
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001792 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 TAG, "Performing receive of " + data.intent
1794 + ": app=" + app
1795 + ", appName=" + app.getPackageName()
1796 + ", pkg=" + packageInfo.getPackageName()
1797 + ", comp=" + data.intent.getComponent().toShortString()
1798 + ", dir=" + packageInfo.getAppDir());
1799
Dianne Hackborn21556372010-02-04 16:34:40 -08001800 ContextImpl context = (ContextImpl)app.getBaseContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 receiver.setOrderedHint(true);
1802 receiver.setResult(data.resultCode, data.resultData,
1803 data.resultExtras);
1804 receiver.setOrderedHint(data.sync);
1805 receiver.onReceive(context.getReceiverRestrictedContext(),
1806 data.intent);
1807 } catch (Exception e) {
1808 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001809 if (DEBUG_BROADCAST) Slog.i(TAG,
1810 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1812 data.resultData, data.resultExtras, data.resultAbort);
1813 } catch (RemoteException ex) {
1814 }
1815 if (!mInstrumentation.onException(receiver, e)) {
1816 throw new RuntimeException(
1817 "Unable to start receiver " + component
1818 + ": " + e.toString(), e);
1819 }
1820 }
1821
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001822 QueuedWork.waitToFinish();
1823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 try {
1825 if (data.sync) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001826 if (DEBUG_BROADCAST) Slog.i(TAG,
1827 "Finishing ordered broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 mgr.finishReceiver(
1829 mAppThread.asBinder(), receiver.getResultCode(),
1830 receiver.getResultData(), receiver.getResultExtras(false),
1831 receiver.getAbortBroadcast());
1832 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001833 if (DEBUG_BROADCAST) Slog.i(TAG,
1834 "Finishing broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
1836 }
1837 } catch (RemoteException ex) {
1838 }
1839 }
1840
Christopher Tate181fafa2009-05-14 11:12:14 -07001841 // Instantiate a BackupAgent and tell it that it's alive
1842 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001843 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001844
1845 // no longer idle; we have backup work to do
1846 unscheduleGcIdler();
1847
1848 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001849 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001850 String packageName = packageInfo.mPackageName;
1851 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001852 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001853 + " already exists");
1854 return;
1855 }
Bob Leee5408332009-09-04 18:31:17 -07001856
Christopher Tate181fafa2009-05-14 11:12:14 -07001857 BackupAgent agent = null;
1858 String classname = data.appInfo.backupAgentName;
1859 if (classname == null) {
1860 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001861 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001862 + packageName);
1863 return;
1864 }
1865 classname = "android.app.FullBackupAgent";
1866 }
1867 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001868 IBinder binder = null;
1869 try {
1870 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1871 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1872
1873 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001874 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001875 + data.appInfo.backupAgentName);
1876
Dianne Hackborn21556372010-02-04 16:34:40 -08001877 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001878 context.init(packageInfo, null, this);
1879 context.setOuterContext(agent);
1880 agent.attach(context);
1881
1882 agent.onCreate();
1883 binder = agent.onBind();
1884 mBackupAgents.put(packageName, agent);
1885 } catch (Exception e) {
1886 // If this is during restore, fail silently; otherwise go
1887 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001888 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001889 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1890 throw e;
1891 }
1892 // falling through with 'binder' still null
1893 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001894
1895 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001896 try {
1897 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1898 } catch (RemoteException e) {
1899 // nothing to do.
1900 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001901 } catch (Exception e) {
1902 throw new RuntimeException("Unable to create BackupAgent "
1903 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1904 }
1905 }
1906
1907 // Tear down a BackupAgent
1908 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001909 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001910
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001911 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001912 String packageName = packageInfo.mPackageName;
1913 BackupAgent agent = mBackupAgents.get(packageName);
1914 if (agent != null) {
1915 try {
1916 agent.onDestroy();
1917 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001918 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001919 e.printStackTrace();
1920 }
1921 mBackupAgents.remove(packageName);
1922 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001923 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001924 }
1925 }
1926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 private final void handleCreateService(CreateServiceData data) {
1928 // If we are getting ready to gc after going to the background, well
1929 // we are back active so skip it.
1930 unscheduleGcIdler();
1931
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001932 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 data.info.applicationInfo);
1934 Service service = null;
1935 try {
1936 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1937 service = (Service) cl.loadClass(data.info.name).newInstance();
1938 } catch (Exception e) {
1939 if (!mInstrumentation.onException(service, e)) {
1940 throw new RuntimeException(
1941 "Unable to instantiate service " + data.info.name
1942 + ": " + e.toString(), e);
1943 }
1944 }
1945
1946 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001947 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948
Dianne Hackborn21556372010-02-04 16:34:40 -08001949 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 context.init(packageInfo, null, this);
1951
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001952 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 context.setOuterContext(service);
1954 service.attach(context, this, data.info.name, data.token, app,
1955 ActivityManagerNative.getDefault());
1956 service.onCreate();
1957 mServices.put(data.token, service);
1958 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001959 ActivityManagerNative.getDefault().serviceDoneExecuting(
1960 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 } catch (RemoteException e) {
1962 // nothing to do.
1963 }
1964 } catch (Exception e) {
1965 if (!mInstrumentation.onException(service, e)) {
1966 throw new RuntimeException(
1967 "Unable to create service " + data.info.name
1968 + ": " + e.toString(), e);
1969 }
1970 }
1971 }
1972
1973 private final void handleBindService(BindServiceData data) {
1974 Service s = mServices.get(data.token);
1975 if (s != null) {
1976 try {
1977 data.intent.setExtrasClassLoader(s.getClassLoader());
1978 try {
1979 if (!data.rebind) {
1980 IBinder binder = s.onBind(data.intent);
1981 ActivityManagerNative.getDefault().publishService(
1982 data.token, data.intent, binder);
1983 } else {
1984 s.onRebind(data.intent);
1985 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001986 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001988 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 } catch (RemoteException ex) {
1990 }
1991 } catch (Exception e) {
1992 if (!mInstrumentation.onException(s, e)) {
1993 throw new RuntimeException(
1994 "Unable to bind to service " + s
1995 + " with " + data.intent + ": " + e.toString(), e);
1996 }
1997 }
1998 }
1999 }
2000
2001 private final void handleUnbindService(BindServiceData data) {
2002 Service s = mServices.get(data.token);
2003 if (s != null) {
2004 try {
2005 data.intent.setExtrasClassLoader(s.getClassLoader());
2006 boolean doRebind = s.onUnbind(data.intent);
2007 try {
2008 if (doRebind) {
2009 ActivityManagerNative.getDefault().unbindFinished(
2010 data.token, data.intent, doRebind);
2011 } else {
2012 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002013 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 }
2015 } catch (RemoteException ex) {
2016 }
2017 } catch (Exception e) {
2018 if (!mInstrumentation.onException(s, e)) {
2019 throw new RuntimeException(
2020 "Unable to unbind to service " + s
2021 + " with " + data.intent + ": " + e.toString(), e);
2022 }
2023 }
2024 }
2025 }
2026
2027 private void handleDumpService(DumpServiceInfo info) {
2028 try {
2029 Service s = mServices.get(info.service);
2030 if (s != null) {
2031 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2032 s.dump(info.fd, pw, info.args);
2033 pw.close();
2034 }
2035 } finally {
2036 synchronized (info) {
2037 info.dumped = true;
2038 info.notifyAll();
2039 }
2040 }
2041 }
2042
2043 private final void handleServiceArgs(ServiceArgsData data) {
2044 Service s = mServices.get(data.token);
2045 if (s != null) {
2046 try {
2047 if (data.args != null) {
2048 data.args.setExtrasClassLoader(s.getClassLoader());
2049 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002050 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002051
2052 QueuedWork.waitToFinish();
2053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002055 ActivityManagerNative.getDefault().serviceDoneExecuting(
2056 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 } catch (RemoteException e) {
2058 // nothing to do.
2059 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002060 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 } catch (Exception e) {
2062 if (!mInstrumentation.onException(s, e)) {
2063 throw new RuntimeException(
2064 "Unable to start service " + s
2065 + " with " + data.args + ": " + e.toString(), e);
2066 }
2067 }
2068 }
2069 }
2070
2071 private final void handleStopService(IBinder token) {
2072 Service s = mServices.remove(token);
2073 if (s != null) {
2074 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002075 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 s.onDestroy();
2077 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002078 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002080 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002082
2083 QueuedWork.waitToFinish();
2084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002086 ActivityManagerNative.getDefault().serviceDoneExecuting(
2087 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 } catch (RemoteException e) {
2089 // nothing to do.
2090 }
2091 } catch (Exception e) {
2092 if (!mInstrumentation.onException(s, e)) {
2093 throw new RuntimeException(
2094 "Unable to stop service " + s
2095 + ": " + e.toString(), e);
2096 }
2097 }
2098 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002099 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 }
2101
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002102 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002104 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002105 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 + " finished=" + r.activity.mFinished);
2107 if (r != null && !r.activity.mFinished) {
2108 if (clearHide) {
2109 r.hideForNow = false;
2110 r.activity.mStartedActivity = false;
2111 }
2112 try {
2113 if (r.pendingIntents != null) {
2114 deliverNewIntents(r, r.pendingIntents);
2115 r.pendingIntents = null;
2116 }
2117 if (r.pendingResults != null) {
2118 deliverResults(r, r.pendingResults);
2119 r.pendingResults = null;
2120 }
2121 r.activity.performResume();
2122
Bob Leee5408332009-09-04 18:31:17 -07002123 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 r.paused = false;
2127 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 r.state = null;
2129 } catch (Exception e) {
2130 if (!mInstrumentation.onException(r.activity, e)) {
2131 throw new RuntimeException(
2132 "Unable to resume activity "
2133 + r.intent.getComponent().toShortString()
2134 + ": " + e.toString(), e);
2135 }
2136 }
2137 }
2138 return r;
2139 }
2140
2141 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2142 // If we are getting ready to gc after going to the background, well
2143 // we are back active so skip it.
2144 unscheduleGcIdler();
2145
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002146 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147
2148 if (r != null) {
2149 final Activity a = r.activity;
2150
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002151 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 TAG, "Resume " + r + " started activity: " +
2153 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2154 + ", finished: " + a.mFinished);
2155
2156 final int forwardBit = isForward ?
2157 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 // If the window hasn't yet been added to the window manager,
2160 // and this guy didn't finish itself or start another activity,
2161 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002162 boolean willBeVisible = !a.mStartedActivity;
2163 if (!willBeVisible) {
2164 try {
2165 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2166 a.getActivityToken());
2167 } catch (RemoteException e) {
2168 }
2169 }
2170 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 r.window = r.activity.getWindow();
2172 View decor = r.window.getDecorView();
2173 decor.setVisibility(View.INVISIBLE);
2174 ViewManager wm = a.getWindowManager();
2175 WindowManager.LayoutParams l = r.window.getAttributes();
2176 a.mDecor = decor;
2177 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2178 l.softInputMode |= forwardBit;
2179 if (a.mVisibleFromClient) {
2180 a.mWindowAdded = true;
2181 wm.addView(decor, l);
2182 }
2183
2184 // If the window has already been added, but during resume
2185 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002186 // window visible.
2187 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002188 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 TAG, "Launch " + r + " mStartedActivity set");
2190 r.hideForNow = true;
2191 }
2192
2193 // The window is now visible if it has been added, we are not
2194 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002195 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002196 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002198 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002199 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 performConfigurationChanged(r.activity, r.newConfig);
2201 r.newConfig = null;
2202 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002203 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 + isForward);
2205 WindowManager.LayoutParams l = r.window.getAttributes();
2206 if ((l.softInputMode
2207 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2208 != forwardBit) {
2209 l.softInputMode = (l.softInputMode
2210 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2211 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002212 if (r.activity.mVisibleFromClient) {
2213 ViewManager wm = a.getWindowManager();
2214 View decor = r.window.getDecorView();
2215 wm.updateViewLayout(decor, l);
2216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 }
2218 r.activity.mVisibleFromServer = true;
2219 mNumVisibleActivities++;
2220 if (r.activity.mVisibleFromClient) {
2221 r.activity.makeVisible();
2222 }
2223 }
2224
2225 r.nextIdle = mNewActivities;
2226 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002227 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 TAG, "Scheduling idle handler for " + r);
2229 Looper.myQueue().addIdleHandler(new Idler());
2230
2231 } else {
2232 // If an exception was thrown when trying to resume, then
2233 // just end this activity.
2234 try {
2235 ActivityManagerNative.getDefault()
2236 .finishActivity(token, Activity.RESULT_CANCELED, null);
2237 } catch (RemoteException ex) {
2238 }
2239 }
2240 }
2241
2242 private int mThumbnailWidth = -1;
2243 private int mThumbnailHeight = -1;
2244
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002245 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 Bitmap thumbnail = null;
2247 try {
2248 int w = mThumbnailWidth;
2249 int h;
2250 if (w < 0) {
2251 Resources res = r.activity.getResources();
2252 mThumbnailHeight = h =
2253 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2254
2255 mThumbnailWidth = w =
2256 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2257 } else {
2258 h = mThumbnailHeight;
2259 }
2260
Jim Miller0b2a6d02010-07-13 18:01:29 -07002261 // On platforms where we don't want thumbnails, set dims to (0,0)
2262 if ((w > 0) && (h > 0)) {
2263 View topView = r.activity.getWindow().getDecorView();
2264
2265 // Maximize bitmap by capturing in native aspect.
2266 if (topView.getWidth() >= topView.getHeight()) {
2267 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2268 } else {
2269 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2270 }
2271
2272 thumbnail.eraseColor(0);
2273 Canvas cv = new Canvas(thumbnail);
2274 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2275 thumbnail = null;
2276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 } catch (Exception e) {
2280 if (!mInstrumentation.onException(r.activity, e)) {
2281 throw new RuntimeException(
2282 "Unable to create thumbnail of "
2283 + r.intent.getComponent().toShortString()
2284 + ": " + e.toString(), e);
2285 }
2286 thumbnail = null;
2287 }
2288
2289 return thumbnail;
2290 }
2291
2292 private final void handlePauseActivity(IBinder token, boolean finished,
2293 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002294 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002296 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 if (userLeaving) {
2298 performUserLeavingActivity(r);
2299 }
Bob Leee5408332009-09-04 18:31:17 -07002300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 r.activity.mConfigChangeFlags |= configChanges;
2302 Bundle state = performPauseActivity(token, finished, true);
2303
2304 // Tell the activity manager we have paused.
2305 try {
2306 ActivityManagerNative.getDefault().activityPaused(token, state);
2307 } catch (RemoteException ex) {
2308 }
2309 }
2310 }
2311
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002312 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 mInstrumentation.callActivityOnUserLeaving(r.activity);
2314 }
2315
2316 final Bundle performPauseActivity(IBinder token, boolean finished,
2317 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002318 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 return r != null ? performPauseActivity(r, finished, saveState) : null;
2320 }
2321
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002322 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 boolean saveState) {
2324 if (r.paused) {
2325 if (r.activity.mFinished) {
2326 // If we are finishing, we won't call onResume() in certain cases.
2327 // So here we likewise don't want to call onPause() if the activity
2328 // isn't resumed.
2329 return null;
2330 }
2331 RuntimeException e = new RuntimeException(
2332 "Performing pause of activity that is not resumed: "
2333 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002334 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 }
2336 Bundle state = null;
2337 if (finished) {
2338 r.activity.mFinished = true;
2339 }
2340 try {
2341 // Next have the activity save its current state and managed dialogs...
2342 if (!r.activity.mFinished && saveState) {
2343 state = new Bundle();
2344 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2345 r.state = state;
2346 }
2347 // Now we are idle.
2348 r.activity.mCalled = false;
2349 mInstrumentation.callActivityOnPause(r.activity);
2350 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2351 if (!r.activity.mCalled) {
2352 throw new SuperNotCalledException(
2353 "Activity " + r.intent.getComponent().toShortString() +
2354 " did not call through to super.onPause()");
2355 }
2356
2357 } catch (SuperNotCalledException e) {
2358 throw e;
2359
2360 } catch (Exception e) {
2361 if (!mInstrumentation.onException(r.activity, e)) {
2362 throw new RuntimeException(
2363 "Unable to pause activity "
2364 + r.intent.getComponent().toShortString()
2365 + ": " + e.toString(), e);
2366 }
2367 }
2368 r.paused = true;
2369 return state;
2370 }
2371
2372 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002373 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 performStopActivityInner(r, null, false);
2375 }
2376
2377 private static class StopInfo {
2378 Bitmap thumbnail;
2379 CharSequence description;
2380 }
2381
2382 private final class ProviderRefCount {
2383 public int count;
2384 ProviderRefCount(int pCount) {
2385 count = pCount;
2386 }
2387 }
2388
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002389 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002391 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 if (r != null) {
2393 if (!keepShown && r.stopped) {
2394 if (r.activity.mFinished) {
2395 // If we are finishing, we won't call onResume() in certain
2396 // cases. So here we likewise don't want to call onStop()
2397 // if the activity isn't resumed.
2398 return;
2399 }
2400 RuntimeException e = new RuntimeException(
2401 "Performing stop of activity that is not resumed: "
2402 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002403 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 }
2405
2406 if (info != null) {
2407 try {
2408 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002409 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 info.description = r.activity.onCreateDescription();
2411 } catch (Exception e) {
2412 if (!mInstrumentation.onException(r.activity, e)) {
2413 throw new RuntimeException(
2414 "Unable to save state of activity "
2415 + r.intent.getComponent().toShortString()
2416 + ": " + e.toString(), e);
2417 }
2418 }
2419 }
2420
2421 if (!keepShown) {
2422 try {
2423 // Now we are idle.
2424 r.activity.performStop();
2425 } catch (Exception e) {
2426 if (!mInstrumentation.onException(r.activity, e)) {
2427 throw new RuntimeException(
2428 "Unable to stop activity "
2429 + r.intent.getComponent().toShortString()
2430 + ": " + e.toString(), e);
2431 }
2432 }
2433 r.stopped = true;
2434 }
2435
2436 r.paused = true;
2437 }
2438 }
2439
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002440 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 View v = r.activity.mDecor;
2442 if (v != null) {
2443 if (show) {
2444 if (!r.activity.mVisibleFromServer) {
2445 r.activity.mVisibleFromServer = true;
2446 mNumVisibleActivities++;
2447 if (r.activity.mVisibleFromClient) {
2448 r.activity.makeVisible();
2449 }
2450 }
2451 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002452 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002453 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 performConfigurationChanged(r.activity, r.newConfig);
2455 r.newConfig = null;
2456 }
2457 } else {
2458 if (r.activity.mVisibleFromServer) {
2459 r.activity.mVisibleFromServer = false;
2460 mNumVisibleActivities--;
2461 v.setVisibility(View.INVISIBLE);
2462 }
2463 }
2464 }
2465 }
2466
2467 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002468 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 r.activity.mConfigChangeFlags |= configChanges;
2470
2471 StopInfo info = new StopInfo();
2472 performStopActivityInner(r, info, show);
2473
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002474 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 TAG, "Finishing stop of " + r + ": show=" + show
2476 + " win=" + r.window);
2477
2478 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 // Tell activity manager we have been stopped.
2481 try {
2482 ActivityManagerNative.getDefault().activityStopped(
2483 r.token, info.thumbnail, info.description);
2484 } catch (RemoteException ex) {
2485 }
2486 }
2487
2488 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002489 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 if (r.stopped) {
2491 r.activity.performRestart();
2492 r.stopped = false;
2493 }
2494 }
2495
2496 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002497 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 if (!show && !r.stopped) {
2499 performStopActivityInner(r, null, show);
2500 } else if (show && r.stopped) {
2501 // If we are getting ready to gc after going to the background, well
2502 // we are back active so skip it.
2503 unscheduleGcIdler();
2504
2505 r.activity.performRestart();
2506 r.stopped = false;
2507 }
2508 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002509 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 TAG, "Handle window " + r + " visibility: " + show);
2511 updateVisibility(r, show);
2512 }
2513 }
2514
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002515 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 final int N = results.size();
2517 for (int i=0; i<N; i++) {
2518 ResultInfo ri = results.get(i);
2519 try {
2520 if (ri.mData != null) {
2521 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2522 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002523 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002524 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 r.activity.dispatchActivityResult(ri.mResultWho,
2526 ri.mRequestCode, ri.mResultCode, ri.mData);
2527 } catch (Exception e) {
2528 if (!mInstrumentation.onException(r.activity, e)) {
2529 throw new RuntimeException(
2530 "Failure delivering result " + ri + " to activity "
2531 + r.intent.getComponent().toShortString()
2532 + ": " + e.toString(), e);
2533 }
2534 }
2535 }
2536 }
2537
2538 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002539 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002540 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 if (r != null) {
2542 final boolean resumed = !r.paused;
2543 if (!r.activity.mFinished && r.activity.mDecor != null
2544 && r.hideForNow && resumed) {
2545 // We had hidden the activity because it started another
2546 // one... we have gotten a result back and we are not
2547 // paused, so make sure our window is visible.
2548 updateVisibility(r, true);
2549 }
2550 if (resumed) {
2551 try {
2552 // Now we are idle.
2553 r.activity.mCalled = false;
2554 mInstrumentation.callActivityOnPause(r.activity);
2555 if (!r.activity.mCalled) {
2556 throw new SuperNotCalledException(
2557 "Activity " + r.intent.getComponent().toShortString()
2558 + " did not call through to super.onPause()");
2559 }
2560 } catch (SuperNotCalledException e) {
2561 throw e;
2562 } catch (Exception e) {
2563 if (!mInstrumentation.onException(r.activity, e)) {
2564 throw new RuntimeException(
2565 "Unable to pause activity "
2566 + r.intent.getComponent().toShortString()
2567 + ": " + e.toString(), e);
2568 }
2569 }
2570 }
2571 deliverResults(r, res.results);
2572 if (resumed) {
2573 mInstrumentation.callActivityOnResume(r.activity);
2574 }
2575 }
2576 }
2577
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002578 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 return performDestroyActivity(token, finishing, 0, false);
2580 }
2581
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002582 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002584 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002585 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 if (r != null) {
2587 r.activity.mConfigChangeFlags |= configChanges;
2588 if (finishing) {
2589 r.activity.mFinished = true;
2590 }
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05002591 if (getNonConfigInstance) {
2592 r.activity.mChangingConfigurations = true;
2593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 if (!r.paused) {
2595 try {
2596 r.activity.mCalled = false;
2597 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002598 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 r.activity.getComponentName().getClassName());
2600 if (!r.activity.mCalled) {
2601 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002602 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 + " did not call through to super.onPause()");
2604 }
2605 } catch (SuperNotCalledException e) {
2606 throw e;
2607 } catch (Exception e) {
2608 if (!mInstrumentation.onException(r.activity, e)) {
2609 throw new RuntimeException(
2610 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002611 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 + ": " + e.toString(), e);
2613 }
2614 }
2615 r.paused = true;
2616 }
2617 if (!r.stopped) {
2618 try {
2619 r.activity.performStop();
2620 } catch (SuperNotCalledException e) {
2621 throw e;
2622 } catch (Exception e) {
2623 if (!mInstrumentation.onException(r.activity, e)) {
2624 throw new RuntimeException(
2625 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002626 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 + ": " + e.toString(), e);
2628 }
2629 }
2630 r.stopped = true;
2631 }
2632 if (getNonConfigInstance) {
2633 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002634 r.lastNonConfigurationInstances
2635 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 } catch (Exception e) {
2637 if (!mInstrumentation.onException(r.activity, e)) {
2638 throw new RuntimeException(
2639 "Unable to retain activity "
2640 + r.intent.getComponent().toShortString()
2641 + ": " + e.toString(), e);
2642 }
2643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 }
2645 try {
2646 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002647 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 if (!r.activity.mCalled) {
2649 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002650 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 " did not call through to super.onDestroy()");
2652 }
2653 if (r.window != null) {
2654 r.window.closeAllPanels();
2655 }
2656 } catch (SuperNotCalledException e) {
2657 throw e;
2658 } catch (Exception e) {
2659 if (!mInstrumentation.onException(r.activity, e)) {
2660 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002661 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2662 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
2664 }
2665 }
2666 mActivities.remove(token);
2667
2668 return r;
2669 }
2670
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002671 private static String safeToComponentShortString(Intent intent) {
2672 ComponentName component = intent.getComponent();
2673 return component == null ? "[Unknown]" : component.toShortString();
2674 }
2675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 private final void handleDestroyActivity(IBinder token, boolean finishing,
2677 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002678 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 configChanges, getNonConfigInstance);
2680 if (r != null) {
2681 WindowManager wm = r.activity.getWindowManager();
2682 View v = r.activity.mDecor;
2683 if (v != null) {
2684 if (r.activity.mVisibleFromServer) {
2685 mNumVisibleActivities--;
2686 }
2687 IBinder wtoken = v.getWindowToken();
2688 if (r.activity.mWindowAdded) {
2689 wm.removeViewImmediate(v);
2690 }
2691 if (wtoken != null) {
2692 WindowManagerImpl.getDefault().closeAll(wtoken,
2693 r.activity.getClass().getName(), "Activity");
2694 }
2695 r.activity.mDecor = null;
2696 }
2697 WindowManagerImpl.getDefault().closeAll(token,
2698 r.activity.getClass().getName(), "Activity");
2699
2700 // Mocked out contexts won't be participating in the normal
2701 // process lifecycle, but if we're running with a proper
2702 // ApplicationContext we need to have it tear down things
2703 // cleanly.
2704 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002705 if (c instanceof ContextImpl) {
2706 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 r.activity.getClass().getName(), "Activity");
2708 }
2709 }
2710 if (finishing) {
2711 try {
2712 ActivityManagerNative.getDefault().activityDestroyed(token);
2713 } catch (RemoteException ex) {
2714 // If the system process has died, it's game over for everyone.
2715 }
2716 }
2717 }
2718
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002719 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 // If we are getting ready to gc after going to the background, well
2721 // we are back active so skip it.
2722 unscheduleGcIdler();
2723
2724 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002725
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002726 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002727 + tmp.token + " with configChanges=0x"
2728 + Integer.toHexString(configChanges));
2729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 // First: make sure we have the most recent configuration and most
2731 // recent version of the activity, or skip it if some previous call
2732 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002733 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 int N = mRelaunchingActivities.size();
2735 IBinder token = tmp.token;
2736 tmp = null;
2737 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002738 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 if (r.token == token) {
2740 tmp = r;
2741 mRelaunchingActivities.remove(i);
2742 i--;
2743 N--;
2744 }
2745 }
Bob Leee5408332009-09-04 18:31:17 -07002746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002748 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 return;
2750 }
Bob Leee5408332009-09-04 18:31:17 -07002751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 if (mPendingConfiguration != null) {
2753 changedConfig = mPendingConfiguration;
2754 mPendingConfiguration = null;
2755 }
2756 }
Bob Leee5408332009-09-04 18:31:17 -07002757
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002758 if (tmp.createdConfig != null) {
2759 // If the activity manager is passing us its current config,
2760 // assume that is really what we want regardless of what we
2761 // may have pending.
2762 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002763 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2764 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2765 if (changedConfig == null
2766 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2767 changedConfig = tmp.createdConfig;
2768 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002769 }
2770 }
2771
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002772 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002773 + tmp.token + ": changedConfig=" + changedConfig);
2774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 // If there was a pending configuration change, execute it first.
2776 if (changedConfig != null) {
2777 handleConfigurationChanged(changedConfig);
2778 }
Bob Leee5408332009-09-04 18:31:17 -07002779
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002780 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002781 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 if (r == null) {
2783 return;
2784 }
Bob Leee5408332009-09-04 18:31:17 -07002785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002787 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 Bundle savedState = null;
2790 if (!r.paused) {
2791 savedState = performPauseActivity(r.token, false, true);
2792 }
Bob Leee5408332009-09-04 18:31:17 -07002793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 r.activity = null;
2797 r.window = null;
2798 r.hideForNow = false;
2799 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002800 // Merge any pending results and pending intents; don't just replace them
2801 if (tmp.pendingResults != null) {
2802 if (r.pendingResults == null) {
2803 r.pendingResults = tmp.pendingResults;
2804 } else {
2805 r.pendingResults.addAll(tmp.pendingResults);
2806 }
2807 }
2808 if (tmp.pendingIntents != null) {
2809 if (r.pendingIntents == null) {
2810 r.pendingIntents = tmp.pendingIntents;
2811 } else {
2812 r.pendingIntents.addAll(tmp.pendingIntents);
2813 }
2814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 r.startsNotResumed = tmp.startsNotResumed;
2816 if (savedState != null) {
2817 r.state = savedState;
2818 }
Bob Leee5408332009-09-04 18:31:17 -07002819
Christopher Tateb70f3df2009-04-07 16:07:59 -07002820 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 }
2822
2823 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002824 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 Bitmap thumbnail = createThumbnailBitmap(r);
2826 CharSequence description = null;
2827 try {
2828 description = r.activity.onCreateDescription();
2829 } catch (Exception e) {
2830 if (!mInstrumentation.onException(r.activity, e)) {
2831 throw new RuntimeException(
2832 "Unable to create description of activity "
2833 + r.intent.getComponent().toShortString()
2834 + ": " + e.toString(), e);
2835 }
2836 }
2837 //System.out.println("Reporting top thumbnail " + thumbnail);
2838 try {
2839 ActivityManagerNative.getDefault().reportThumbnail(
2840 token, thumbnail, description);
2841 } catch (RemoteException ex) {
2842 }
2843 }
2844
2845 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2846 boolean allActivities, Configuration newConfig) {
2847 ArrayList<ComponentCallbacks> callbacks
2848 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002851 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002853 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 Activity a = ar.activity;
2855 if (a != null) {
2856 if (!ar.activity.mFinished && (allActivities ||
2857 (a != null && !ar.paused))) {
2858 // If the activity is currently resumed, its configuration
2859 // needs to change right now.
2860 callbacks.add(a);
2861 } else if (newConfig != null) {
2862 // Otherwise, we will tell it about the change
2863 // the next time it is resumed or shown. Note that
2864 // the activity manager may, before then, decide the
2865 // activity needs to be destroyed to handle its new
2866 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002867 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002868 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 ar.newConfig = newConfig;
2870 }
2871 }
2872 }
2873 }
2874 if (mServices.size() > 0) {
2875 Iterator<Service> it = mServices.values().iterator();
2876 while (it.hasNext()) {
2877 callbacks.add(it.next());
2878 }
2879 }
2880 synchronized (mProviderMap) {
2881 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002882 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 while (it.hasNext()) {
2884 callbacks.add(it.next().mLocalProvider);
2885 }
2886 }
2887 }
2888 final int N = mAllApplications.size();
2889 for (int i=0; i<N; i++) {
2890 callbacks.add(mAllApplications.get(i));
2891 }
Bob Leee5408332009-09-04 18:31:17 -07002892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 return callbacks;
2894 }
Bob Leee5408332009-09-04 18:31:17 -07002895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 private final void performConfigurationChanged(
2897 ComponentCallbacks cb, Configuration config) {
2898 // Only for Activity objects, check that they actually call up to their
2899 // superclass implementation. ComponentCallbacks is an interface, so
2900 // we check the runtime type and act accordingly.
2901 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2902 if (activity != null) {
2903 activity.mCalled = false;
2904 }
Bob Leee5408332009-09-04 18:31:17 -07002905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 boolean shouldChangeConfig = false;
2907 if ((activity == null) || (activity.mCurrentConfig == null)) {
2908 shouldChangeConfig = true;
2909 } else {
Bob Leee5408332009-09-04 18:31:17 -07002910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 // If the new config is the same as the config this Activity
2912 // is already running with then don't bother calling
2913 // onConfigurationChanged
2914 int diff = activity.mCurrentConfig.diff(config);
2915 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 // If this activity doesn't handle any of the config changes
2918 // then don't bother calling onConfigurationChanged as we're
2919 // going to destroy it.
2920 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2921 shouldChangeConfig = true;
2922 }
2923 }
2924 }
Bob Leee5408332009-09-04 18:31:17 -07002925
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002926 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002927 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 if (shouldChangeConfig) {
2929 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 if (activity != null) {
2932 if (!activity.mCalled) {
2933 throw new SuperNotCalledException(
2934 "Activity " + activity.getLocalClassName() +
2935 " did not call through to super.onConfigurationChanged()");
2936 }
2937 activity.mConfigChangeFlags = 0;
2938 activity.mCurrentConfig = new Configuration(config);
2939 }
2940 }
2941 }
2942
Dianne Hackbornae078162010-03-18 11:29:37 -07002943 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002944 if (mResConfiguration == null) {
2945 mResConfiguration = new Configuration();
2946 }
2947 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002948 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002949 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002950 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002951 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002952 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002953 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002954
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002955 // set it for java, this also affects newly created Resources
2956 if (config.locale != null) {
2957 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 }
Bob Leee5408332009-09-04 18:31:17 -07002959
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002960 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07002961
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002962 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002963 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002964
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002965 Iterator<WeakReference<Resources>> it =
2966 mActiveResources.values().iterator();
2967 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
2968 // mActiveResources.entrySet().iterator();
2969 while (it.hasNext()) {
2970 WeakReference<Resources> v = it.next();
2971 Resources r = v.get();
2972 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002973 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002974 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002975 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002976 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002977 // + " " + r + ": " + r.getConfiguration());
2978 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002979 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002980 it.remove();
2981 }
2982 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002983
2984 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002985 }
2986
2987 final void handleConfigurationChanged(Configuration config) {
2988
2989 ArrayList<ComponentCallbacks> callbacks = null;
2990
2991 synchronized (mPackages) {
2992 if (mPendingConfiguration != null) {
2993 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
2994 config = mPendingConfiguration;
2995 }
2996 mPendingConfiguration = null;
2997 }
2998
2999 if (config == null) {
3000 return;
3001 }
3002
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003003 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003004 + config);
3005
3006 applyConfigurationToResourcesLocked(config);
3007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 if (mConfiguration == null) {
3009 mConfiguration = new Configuration();
3010 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003011 if (!mConfiguration.isOtherSeqNewer(config)) {
3012 return;
3013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 callbacks = collectComponentCallbacksLocked(false, config);
3017 }
Bob Leee5408332009-09-04 18:31:17 -07003018
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003019 if (callbacks != null) {
3020 final int N = callbacks.size();
3021 for (int i=0; i<N; i++) {
3022 performConfigurationChanged(callbacks.get(i), config);
3023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 }
3025 }
3026
3027 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003028 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 if (r == null || r.activity == null) {
3030 return;
3031 }
Bob Leee5408332009-09-04 18:31:17 -07003032
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003033 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003034 + r.activityInfo.name);
3035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 performConfigurationChanged(r.activity, mConfiguration);
3037 }
3038
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003039 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003040 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003041 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003042 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3043 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003044 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003045 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003046 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003047 } finally {
3048 try {
3049 pcd.fd.close();
3050 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003051 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003052 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003053 }
3054 } else {
3055 Debug.stopMethodTracing();
3056 }
3057 }
Bob Leee5408332009-09-04 18:31:17 -07003058
Andy McFadden824c5102010-07-09 16:26:57 -07003059 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3060 if (managed) {
3061 try {
3062 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3063 } catch (IOException e) {
3064 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3065 + " -- can the process access this path?");
3066 } finally {
3067 try {
3068 dhd.fd.close();
3069 } catch (IOException e) {
3070 Slog.w(TAG, "Failure closing profile fd", e);
3071 }
3072 }
3073 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003074 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003075 }
3076 }
3077
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003078 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3079 boolean hasPkgInfo = false;
3080 if (packages != null) {
3081 for (int i=packages.length-1; i>=0; i--) {
3082 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3083 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003084 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003085 ref = mPackages.get(packages[i]);
3086 if (ref != null && ref.get() != null) {
3087 hasPkgInfo = true;
3088 } else {
3089 ref = mResourcePackages.get(packages[i]);
3090 if (ref != null && ref.get() != null) {
3091 hasPkgInfo = true;
3092 }
3093 }
3094 }
3095 mPackages.remove(packages[i]);
3096 mResourcePackages.remove(packages[i]);
3097 }
3098 }
3099 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3100 hasPkgInfo);
3101 }
3102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 final void handleLowMemory() {
3104 ArrayList<ComponentCallbacks> callbacks
3105 = new ArrayList<ComponentCallbacks>();
3106
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003107 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 callbacks = collectComponentCallbacksLocked(true, null);
3109 }
Bob Leee5408332009-09-04 18:31:17 -07003110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 final int N = callbacks.size();
3112 for (int i=0; i<N; i++) {
3113 callbacks.get(i).onLowMemory();
3114 }
3115
Chris Tatece229052009-03-25 16:44:52 -07003116 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3117 if (Process.myUid() != Process.SYSTEM_UID) {
3118 int sqliteReleased = SQLiteDatabase.releaseMemory();
3119 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3120 }
Bob Leee5408332009-09-04 18:31:17 -07003121
Mike Reedcaf0df12009-04-27 14:32:05 -04003122 // Ask graphics to free up as much as possible (font/image caches)
3123 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124
3125 BinderInternal.forceGc("mem");
3126 }
3127
3128 private final void handleBindApplication(AppBindData data) {
3129 mBoundApplication = data;
3130 mConfiguration = new Configuration(data.config);
3131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003133 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 android.ddm.DdmHandleAppName.setAppName(data.processName);
3135
3136 /*
3137 * Before spawning a new process, reset the time zone to be the system time zone.
3138 * This needs to be done because the system time zone could have changed after the
3139 * the spawning of this process. Without doing this this process would have the incorrect
3140 * system time zone.
3141 */
3142 TimeZone.setDefault(null);
3143
3144 /*
3145 * Initialize the default locale in this process for the reasons we set the time zone.
3146 */
3147 Locale.setDefault(data.config.locale);
3148
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003149 /*
3150 * Update the system configuration since its preloaded and might not
3151 * reflect configuration changes. The configuration object passed
3152 * in AppBindData can be safely assumed to be up to date
3153 */
3154 Resources.getSystem().updateConfiguration(mConfiguration, null);
3155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 data.info = getPackageInfoNoCheck(data.appInfo);
3157
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003158 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003159 * For system applications on userdebug/eng builds, log stack
3160 * traces of disk and network access to dropbox for analysis.
3161 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003162 if ((data.appInfo.flags &
3163 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003164 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3165 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003166 }
3167
3168 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003169 * Switch this process to density compatibility mode if needed.
3170 */
3171 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3172 == 0) {
3173 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3174 }
Bob Leee5408332009-09-04 18:31:17 -07003175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3177 // XXX should have option to change the port.
3178 Debug.changeDebugPort(8100);
3179 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003180 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 + " is waiting for the debugger on port 8100...");
3182
3183 IActivityManager mgr = ActivityManagerNative.getDefault();
3184 try {
3185 mgr.showWaitingForDebugger(mAppThread, true);
3186 } catch (RemoteException ex) {
3187 }
3188
3189 Debug.waitForDebugger();
3190
3191 try {
3192 mgr.showWaitingForDebugger(mAppThread, false);
3193 } catch (RemoteException ex) {
3194 }
3195
3196 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003197 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 + " can be debugged on port 8100...");
3199 }
3200 }
3201
3202 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003203 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 appContext.init(data.info, null, this);
3205 InstrumentationInfo ii = null;
3206 try {
3207 ii = appContext.getPackageManager().
3208 getInstrumentationInfo(data.instrumentationName, 0);
3209 } catch (PackageManager.NameNotFoundException e) {
3210 }
3211 if (ii == null) {
3212 throw new RuntimeException(
3213 "Unable to find instrumentation info for: "
3214 + data.instrumentationName);
3215 }
3216
3217 mInstrumentationAppDir = ii.sourceDir;
3218 mInstrumentationAppPackage = ii.packageName;
3219 mInstrumentedAppDir = data.info.getAppDir();
3220
3221 ApplicationInfo instrApp = new ApplicationInfo();
3222 instrApp.packageName = ii.packageName;
3223 instrApp.sourceDir = ii.sourceDir;
3224 instrApp.publicSourceDir = ii.publicSourceDir;
3225 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003226 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003227 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003229 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 instrContext.init(pi, null, this);
3231
3232 try {
3233 java.lang.ClassLoader cl = instrContext.getClassLoader();
3234 mInstrumentation = (Instrumentation)
3235 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3236 } catch (Exception e) {
3237 throw new RuntimeException(
3238 "Unable to instantiate instrumentation "
3239 + data.instrumentationName + ": " + e.toString(), e);
3240 }
3241
3242 mInstrumentation.init(this, instrContext, appContext,
3243 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3244
3245 if (data.profileFile != null && !ii.handleProfiling) {
3246 data.handlingProfiling = true;
3247 File file = new File(data.profileFile);
3248 file.getParentFile().mkdirs();
3249 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3250 }
3251
3252 try {
3253 mInstrumentation.onCreate(data.instrumentationArgs);
3254 }
3255 catch (Exception e) {
3256 throw new RuntimeException(
3257 "Exception thrown in onCreate() of "
3258 + data.instrumentationName + ": " + e.toString(), e);
3259 }
3260
3261 } else {
3262 mInstrumentation = new Instrumentation();
3263 }
3264
Christopher Tate181fafa2009-05-14 11:12:14 -07003265 // If the app is being launched for full backup or restore, bring it up in
3266 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003267 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 mInitialApplication = app;
3269
3270 List<ProviderInfo> providers = data.providers;
3271 if (providers != null) {
3272 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003273 // For process that contain content providers, we want to
3274 // ensure that the JIT is enabled "at some point".
3275 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 }
3277
3278 try {
3279 mInstrumentation.callApplicationOnCreate(app);
3280 } catch (Exception e) {
3281 if (!mInstrumentation.onException(app, e)) {
3282 throw new RuntimeException(
3283 "Unable to create application " + app.getClass().getName()
3284 + ": " + e.toString(), e);
3285 }
3286 }
3287 }
3288
3289 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3290 IActivityManager am = ActivityManagerNative.getDefault();
3291 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3292 Debug.stopMethodTracing();
3293 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003294 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 // + ", app thr: " + mAppThread);
3296 try {
3297 am.finishInstrumentation(mAppThread, resultCode, results);
3298 } catch (RemoteException ex) {
3299 }
3300 }
3301
3302 private final void installContentProviders(
3303 Context context, List<ProviderInfo> providers) {
3304 final ArrayList<IActivityManager.ContentProviderHolder> results =
3305 new ArrayList<IActivityManager.ContentProviderHolder>();
3306
3307 Iterator<ProviderInfo> i = providers.iterator();
3308 while (i.hasNext()) {
3309 ProviderInfo cpi = i.next();
3310 StringBuilder buf = new StringBuilder(128);
3311 buf.append("Publishing provider ");
3312 buf.append(cpi.authority);
3313 buf.append(": ");
3314 buf.append(cpi.name);
3315 Log.i(TAG, buf.toString());
3316 IContentProvider cp = installProvider(context, null, cpi, false);
3317 if (cp != null) {
3318 IActivityManager.ContentProviderHolder cph =
3319 new IActivityManager.ContentProviderHolder(cpi);
3320 cph.provider = cp;
3321 results.add(cph);
3322 // Don't ever unload this provider from the process.
3323 synchronized(mProviderMap) {
3324 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3325 }
3326 }
3327 }
3328
3329 try {
3330 ActivityManagerNative.getDefault().publishContentProviders(
3331 getApplicationThread(), results);
3332 } catch (RemoteException ex) {
3333 }
3334 }
3335
3336 private final IContentProvider getProvider(Context context, String name) {
3337 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003338 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 if (pr != null) {
3340 return pr.mProvider;
3341 }
3342 }
3343
3344 IActivityManager.ContentProviderHolder holder = null;
3345 try {
3346 holder = ActivityManagerNative.getDefault().getContentProvider(
3347 getApplicationThread(), name);
3348 } catch (RemoteException ex) {
3349 }
3350 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003351 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 return null;
3353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354
3355 IContentProvider prov = installProvider(context, holder.provider,
3356 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003357 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 if (holder.noReleaseNeeded || holder.provider == null) {
3359 // We are not going to release the provider if it is an external
3360 // provider that doesn't care about being released, or if it is
3361 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003362 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 synchronized(mProviderMap) {
3364 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3365 }
3366 }
3367 return prov;
3368 }
3369
3370 public final IContentProvider acquireProvider(Context c, String name) {
3371 IContentProvider provider = getProvider(c, name);
3372 if(provider == null)
3373 return null;
3374 IBinder jBinder = provider.asBinder();
3375 synchronized(mProviderMap) {
3376 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3377 if(prc == null) {
3378 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3379 } else {
3380 prc.count++;
3381 } //end else
3382 } //end synchronized
3383 return provider;
3384 }
3385
3386 public final boolean releaseProvider(IContentProvider provider) {
3387 if(provider == null) {
3388 return false;
3389 }
3390 IBinder jBinder = provider.asBinder();
3391 synchronized(mProviderMap) {
3392 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3393 if(prc == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003394 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldnt be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 return false;
3396 } else {
3397 prc.count--;
3398 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003399 // Schedule the actual remove asynchronously, since we
3400 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003401 // TODO: it would be nice to post a delayed message, so
3402 // if we come back and need the same provider quickly
3403 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003404 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3405 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 } //end if
3407 } //end else
3408 } //end synchronized
3409 return true;
3410 }
3411
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003412 final void completeRemoveProvider(IContentProvider provider) {
3413 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003414 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003415 synchronized(mProviderMap) {
3416 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3417 if(prc != null && prc.count == 0) {
3418 mProviderRefCountMap.remove(jBinder);
3419 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003420 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003421 }
3422 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003423
3424 if (name != null) {
3425 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003426 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003427 "ActivityManagerNative.removeContentProvider(" + name);
3428 ActivityManagerNative.getDefault().removeContentProvider(
3429 getApplicationThread(), name);
3430 } catch (RemoteException e) {
3431 //do nothing content provider object is dead any way
3432 } //end catch
3433 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003434 }
3435
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003436 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003438 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 }
3440 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003442 String name = null;
3443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003445 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003447 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 IBinder myBinder = pr.mProvider.asBinder();
3449 if (myBinder == providerBinder) {
3450 //find if its published by this process itself
3451 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003452 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003453 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003455 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 "death recipient");
3457 //content provider is in another process
3458 myBinder.unlinkToDeath(pr, 0);
3459 iter.remove();
3460 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003461 if(name == null) {
3462 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 }
3464 } //end if myBinder
3465 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003466
3467 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 }
3469
3470 final void removeDeadProvider(String name, IContentProvider provider) {
3471 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003472 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003474 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003475 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003476 if (removed != null) {
3477 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 }
3480 }
3481 }
3482
3483 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003484 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003486 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003487 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003488 if (removed != null) {
3489 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 }
3492 }
3493
3494 private final IContentProvider installProvider(Context context,
3495 IContentProvider provider, ProviderInfo info, boolean noisy) {
3496 ContentProvider localProvider = null;
3497 if (provider == null) {
3498 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003499 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 + info.name);
3501 }
3502 Context c = null;
3503 ApplicationInfo ai = info.applicationInfo;
3504 if (context.getPackageName().equals(ai.packageName)) {
3505 c = context;
3506 } else if (mInitialApplication != null &&
3507 mInitialApplication.getPackageName().equals(ai.packageName)) {
3508 c = mInitialApplication;
3509 } else {
3510 try {
3511 c = context.createPackageContext(ai.packageName,
3512 Context.CONTEXT_INCLUDE_CODE);
3513 } catch (PackageManager.NameNotFoundException e) {
3514 }
3515 }
3516 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003517 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 ai.packageName +
3519 " while loading content provider " +
3520 info.name);
3521 return null;
3522 }
3523 try {
3524 final java.lang.ClassLoader cl = c.getClassLoader();
3525 localProvider = (ContentProvider)cl.
3526 loadClass(info.name).newInstance();
3527 provider = localProvider.getIContentProvider();
3528 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003529 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 info.name + " from sourceDir " +
3531 info.applicationInfo.sourceDir);
3532 return null;
3533 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003534 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 TAG, "Instantiating local provider " + info.name);
3536 // XXX Need to create the correct context for this provider.
3537 localProvider.attachInfo(c, info);
3538 } catch (java.lang.Exception e) {
3539 if (!mInstrumentation.onException(null, e)) {
3540 throw new RuntimeException(
3541 "Unable to get provider " + info.name
3542 + ": " + e.toString(), e);
3543 }
3544 return null;
3545 }
3546 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003547 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 + info.name);
3549 }
3550
3551 synchronized (mProviderMap) {
3552 // Cache the pointer for the remote provider.
3553 String names[] = PATTERN_SEMICOLON.split(info.authority);
3554 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003555 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 localProvider);
3557 try {
3558 provider.asBinder().linkToDeath(pr, 0);
3559 mProviderMap.put(names[i], pr);
3560 } catch (RemoteException e) {
3561 return null;
3562 }
3563 }
3564 if (localProvider != null) {
3565 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003566 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 }
3568 }
3569
3570 return provider;
3571 }
3572
3573 private final void attach(boolean system) {
3574 sThreadLocal.set(this);
3575 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003577 ViewRoot.addFirstDrawHandler(new Runnable() {
3578 public void run() {
3579 ensureJitEnabled();
3580 }
3581 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3583 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3584 IActivityManager mgr = ActivityManagerNative.getDefault();
3585 try {
3586 mgr.attachApplication(mAppThread);
3587 } catch (RemoteException ex) {
3588 }
3589 } else {
3590 // Don't set application object here -- if the system crashes,
3591 // we can't display an alert, we just want to die die die.
3592 android.ddm.DdmHandleAppName.setAppName("system_process");
3593 try {
3594 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003595 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 context.init(getSystemContext().mPackageInfo, null, this);
3597 Application app = Instrumentation.newApplication(Application.class, context);
3598 mAllApplications.add(app);
3599 mInitialApplication = app;
3600 app.onCreate();
3601 } catch (Exception e) {
3602 throw new RuntimeException(
3603 "Unable to instantiate Application():" + e.toString(), e);
3604 }
3605 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003606
3607 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3608 public void onConfigurationChanged(Configuration newConfig) {
3609 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003610 // We need to apply this change to the resources
3611 // immediately, because upon returning the view
3612 // hierarchy will be informed about it.
3613 if (applyConfigurationToResourcesLocked(newConfig)) {
3614 // This actually changed the resources! Tell
3615 // everyone about it.
3616 if (mPendingConfiguration == null ||
3617 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3618 mPendingConfiguration = newConfig;
3619
3620 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3621 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003622 }
3623 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003624 }
3625 public void onLowMemory() {
3626 }
3627 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 }
3629
3630 private final void detach()
3631 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 sThreadLocal.set(null);
3633 }
3634
3635 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003636 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 ActivityThread thread = new ActivityThread();
3638 thread.attach(true);
3639 return thread;
3640 }
3641
3642 public final void installSystemProviders(List providers) {
3643 if (providers != null) {
3644 installContentProviders(mInitialApplication,
3645 (List<ProviderInfo>)providers);
3646 }
3647 }
3648
3649 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003650 SamplingProfilerIntegration.start();
3651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 Process.setArgV0("<pre-initialized>");
3653
3654 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003655 if (sMainThreadHandler == null) {
3656 sMainThreadHandler = new Handler();
3657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658
3659 ActivityThread thread = new ActivityThread();
3660 thread.attach(false);
3661
3662 Looper.loop();
3663
3664 if (Process.supportsProcesses()) {
3665 throw new RuntimeException("Main thread loop unexpectedly exited");
3666 }
3667
3668 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003669 String name = (thread.mInitialApplication != null)
3670 ? thread.mInitialApplication.getPackageName()
3671 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003672 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 }
3674}