blob: ca6fc8aa035bb3ea2b8128b2d1124100a94efe72 [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;
33import android.content.pm.ProviderInfo;
34import android.content.pm.ServiceInfo;
35import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070036import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.database.sqlite.SQLiteDatabase;
40import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080041import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.graphics.Bitmap;
43import android.graphics.Canvas;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070044import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Bundle;
46import android.os.Debug;
47import android.os.Handler;
48import android.os.IBinder;
49import android.os.Looper;
50import android.os.Message;
51import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070052import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Process;
54import android.os.RemoteException;
55import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070056import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.SystemClock;
58import android.util.AndroidRuntimeException;
59import android.util.Config;
60import android.util.DisplayMetrics;
61import android.util.EventLog;
62import android.util.Log;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080063import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.Display;
65import android.view.View;
66import android.view.ViewDebug;
67import android.view.ViewManager;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080068import android.view.ViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.view.Window;
70import android.view.WindowManager;
71import android.view.WindowManagerImpl;
72
73import com.android.internal.os.BinderInternal;
74import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070075import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
78
79import java.io.File;
80import java.io.FileDescriptor;
81import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070082import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import java.io.PrintWriter;
84import java.lang.ref.WeakReference;
85import java.util.ArrayList;
86import java.util.HashMap;
87import java.util.Iterator;
88import java.util.List;
89import java.util.Locale;
90import java.util.Map;
91import java.util.TimeZone;
92import java.util.regex.Pattern;
93
Bob Leee5408332009-09-04 18:31:17 -070094import dalvik.system.SamplingProfiler;
95
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096final class SuperNotCalledException extends AndroidRuntimeException {
97 public SuperNotCalledException(String msg) {
98 super(msg);
99 }
100}
101
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700102final class RemoteServiceException extends AndroidRuntimeException {
103 public RemoteServiceException(String msg) {
104 super(msg);
105 }
106}
107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108/**
109 * This manages the execution of the main thread in an
110 * application process, scheduling and executing activities,
111 * broadcasts, and other operations on it as the activity
112 * manager requests.
113 *
114 * {@hide}
115 */
116public final class ActivityThread {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700117 static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700118 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700120 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
121 static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700122 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700123 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700124 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
126 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
127 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
128 private static final int LOG_ON_PAUSE_CALLED = 30021;
129 private static final int LOG_ON_RESUME_CALLED = 30022;
130
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700131 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700132
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700133 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700135 final ApplicationThread mAppThread = new ApplicationThread();
136 final Looper mLooper = Looper.myLooper();
137 final H mH = new H();
138 final HashMap<IBinder, ActivityClientRecord> mActivities
139 = new HashMap<IBinder, ActivityClientRecord>();
140 // List of new activities (via ActivityRecord.nextIdle) that should
141 // be reported when next we idle.
142 ActivityClientRecord mNewActivities = null;
143 // Number of activities that are currently visible on-screen.
144 int mNumVisibleActivities = 0;
145 final HashMap<IBinder, Service> mServices
146 = new HashMap<IBinder, Service>();
147 AppBindData mBoundApplication;
148 Configuration mConfiguration;
149 Configuration mResConfiguration;
150 Application mInitialApplication;
151 final ArrayList<Application> mAllApplications
152 = new ArrayList<Application>();
153 // set of instantiated backup agents, keyed by package name
154 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700155 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700156 Instrumentation mInstrumentation;
157 String mInstrumentationAppDir = null;
158 String mInstrumentationAppPackage = null;
159 String mInstrumentedAppDir = null;
160 boolean mSystemThread = false;
161 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700163 // These can be accessed by multiple threads; mPackages is the lock.
164 // XXX For now we keep around information about all packages we have
165 // seen, not removing entries from this map.
166 final HashMap<String, WeakReference<LoadedApk>> mPackages
167 = new HashMap<String, WeakReference<LoadedApk>>();
168 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
169 = new HashMap<String, WeakReference<LoadedApk>>();
170 Display mDisplay = null;
171 DisplayMetrics mDisplayMetrics = null;
172 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
173 = new HashMap<ResourcesKey, WeakReference<Resources> >();
174 final ArrayList<ActivityClientRecord> mRelaunchingActivities
175 = new ArrayList<ActivityClientRecord>();
176 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700178 // The lock of mProviderMap protects the following variables.
179 final HashMap<String, ProviderClientRecord> mProviderMap
180 = new HashMap<String, ProviderClientRecord>();
181 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
182 = new HashMap<IBinder, ProviderRefCount>();
183 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
184 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700186 final GcIdler mGcIdler = new GcIdler();
187 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700189 static Handler sMainThreadHandler; // set once in main()
190
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700191 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700193 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 Intent intent;
195 Bundle state;
196 Activity activity;
197 Window window;
198 Activity parent;
199 String embeddedID;
200 Object lastNonConfigurationInstance;
201 HashMap<String,Object> lastNonConfigurationChildInstances;
202 boolean paused;
203 boolean stopped;
204 boolean hideForNow;
205 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700206 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700207 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
209 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700210 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
212 List<ResultInfo> pendingResults;
213 List<Intent> pendingIntents;
214
215 boolean startsNotResumed;
216 boolean isForward;
217
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700218 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 parent = null;
220 embeddedID = null;
221 paused = false;
222 stopped = false;
223 hideForNow = false;
224 nextIdle = null;
225 }
226
227 public String toString() {
228 ComponentName componentName = intent.getComponent();
229 return "ActivityRecord{"
230 + Integer.toHexString(System.identityHashCode(this))
231 + " token=" + token + " " + (componentName == null
232 ? "no component name" : componentName.toShortString())
233 + "}";
234 }
235 }
236
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700237 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 final String mName;
239 final IContentProvider mProvider;
240 final ContentProvider mLocalProvider;
241
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700242 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 ContentProvider localProvider) {
244 mName = name;
245 mProvider = provider;
246 mLocalProvider = localProvider;
247 }
248
249 public void binderDied() {
250 removeDeadProvider(mName, mProvider);
251 }
252 }
253
254 private static final class NewIntentData {
255 List<Intent> intents;
256 IBinder token;
257 public String toString() {
258 return "NewIntentData{intents=" + intents + " token=" + token + "}";
259 }
260 }
261
262 private static final class ReceiverData {
263 Intent intent;
264 ActivityInfo info;
265 int resultCode;
266 String resultData;
267 Bundle resultExtras;
268 boolean sync;
269 boolean resultAbort;
270 public String toString() {
271 return "ReceiverData{intent=" + intent + " packageName=" +
272 info.packageName + " resultCode=" + resultCode
273 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
274 }
275 }
276
Christopher Tate181fafa2009-05-14 11:12:14 -0700277 private static final class CreateBackupAgentData {
278 ApplicationInfo appInfo;
279 int backupMode;
280 public String toString() {
281 return "CreateBackupAgentData{appInfo=" + appInfo
282 + " backupAgent=" + appInfo.backupAgentName
283 + " mode=" + backupMode + "}";
284 }
285 }
Bob Leee5408332009-09-04 18:31:17 -0700286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 private static final class CreateServiceData {
288 IBinder token;
289 ServiceInfo info;
290 Intent intent;
291 public String toString() {
292 return "CreateServiceData{token=" + token + " className="
293 + info.name + " packageName=" + info.packageName
294 + " intent=" + intent + "}";
295 }
296 }
297
298 private static final class BindServiceData {
299 IBinder token;
300 Intent intent;
301 boolean rebind;
302 public String toString() {
303 return "BindServiceData{token=" + token + " intent=" + intent + "}";
304 }
305 }
306
307 private static final class ServiceArgsData {
308 IBinder token;
309 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700310 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 Intent args;
312 public String toString() {
313 return "ServiceArgsData{token=" + token + " startId=" + startId
314 + " args=" + args + "}";
315 }
316 }
317
318 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700319 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 String processName;
321 ApplicationInfo appInfo;
322 List<ProviderInfo> providers;
323 ComponentName instrumentationName;
324 String profileFile;
325 Bundle instrumentationArgs;
326 IInstrumentationWatcher instrumentationWatcher;
327 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700328 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 Configuration config;
330 boolean handlingProfiling;
331 public String toString() {
332 return "AppBindData{appInfo=" + appInfo + "}";
333 }
334 }
335
336 private static final class DumpServiceInfo {
337 FileDescriptor fd;
338 IBinder service;
339 String[] args;
340 boolean dumped;
341 }
342
343 private static final class ResultData {
344 IBinder token;
345 List<ResultInfo> results;
346 public String toString() {
347 return "ResultData{token=" + token + " results" + results + "}";
348 }
349 }
350
351 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800352 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 String what;
354 String who;
355 }
356
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700357 private static final class ProfilerControlData {
358 String path;
359 ParcelFileDescriptor fd;
360 }
361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 private final class ApplicationThread extends ApplicationThreadNative {
363 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
364 private static final String ONE_COUNT_COLUMN = "%17s %8d";
365 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Noric3849202010-03-09 10:47:25 -0800366 private static final String DB_INFO_FORMAT = " %8d %8d %10d %s";
Bob Leee5408332009-09-04 18:31:17 -0700367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 // Formatting for checkin service - update version if row format changes
369 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 public final void schedulePauseActivity(IBinder token, boolean finished,
372 boolean userLeaving, int configChanges) {
373 queueOrSendMessage(
374 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
375 token,
376 (userLeaving ? 1 : 0),
377 configChanges);
378 }
379
380 public final void scheduleStopActivity(IBinder token, boolean showWindow,
381 int configChanges) {
382 queueOrSendMessage(
383 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
384 token, 0, configChanges);
385 }
386
387 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
388 queueOrSendMessage(
389 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
390 token);
391 }
392
393 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
394 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
395 }
396
397 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
398 ResultData res = new ResultData();
399 res.token = token;
400 res.results = results;
401 queueOrSendMessage(H.SEND_RESULT, res);
402 }
403
404 // we use token to identify this activity without having to send the
405 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700406 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
408 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700409 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410
411 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700412 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 r.intent = intent;
414 r.activityInfo = info;
415 r.state = state;
416
417 r.pendingResults = pendingResults;
418 r.pendingIntents = pendingNewIntents;
419
420 r.startsNotResumed = notResumed;
421 r.isForward = isForward;
422
423 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
424 }
425
426 public final void scheduleRelaunchActivity(IBinder token,
427 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800428 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700429 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430
431 r.token = token;
432 r.pendingResults = pendingResults;
433 r.pendingIntents = pendingNewIntents;
434 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800435 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800437 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 mRelaunchingActivities.add(r);
439 }
Bob Leee5408332009-09-04 18:31:17 -0700440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
442 }
443
444 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
445 NewIntentData data = new NewIntentData();
446 data.intents = intents;
447 data.token = token;
448
449 queueOrSendMessage(H.NEW_INTENT, data);
450 }
451
452 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
453 int configChanges) {
454 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
455 configChanges);
456 }
457
458 public final void scheduleReceiver(Intent intent, ActivityInfo info,
459 int resultCode, String data, Bundle extras, boolean sync) {
460 ReceiverData r = new ReceiverData();
461
462 r.intent = intent;
463 r.info = info;
464 r.resultCode = resultCode;
465 r.resultData = data;
466 r.resultExtras = extras;
467 r.sync = sync;
468
469 queueOrSendMessage(H.RECEIVER, r);
470 }
471
Christopher Tate181fafa2009-05-14 11:12:14 -0700472 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
473 CreateBackupAgentData d = new CreateBackupAgentData();
474 d.appInfo = app;
475 d.backupMode = backupMode;
476
477 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
478 }
479
480 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
481 CreateBackupAgentData d = new CreateBackupAgentData();
482 d.appInfo = app;
483
484 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
485 }
486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 public final void scheduleCreateService(IBinder token,
488 ServiceInfo info) {
489 CreateServiceData s = new CreateServiceData();
490 s.token = token;
491 s.info = info;
492
493 queueOrSendMessage(H.CREATE_SERVICE, s);
494 }
495
496 public final void scheduleBindService(IBinder token, Intent intent,
497 boolean rebind) {
498 BindServiceData s = new BindServiceData();
499 s.token = token;
500 s.intent = intent;
501 s.rebind = rebind;
502
503 queueOrSendMessage(H.BIND_SERVICE, s);
504 }
505
506 public final void scheduleUnbindService(IBinder token, Intent intent) {
507 BindServiceData s = new BindServiceData();
508 s.token = token;
509 s.intent = intent;
510
511 queueOrSendMessage(H.UNBIND_SERVICE, s);
512 }
513
514 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700515 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 ServiceArgsData s = new ServiceArgsData();
517 s.token = token;
518 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700519 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 s.args = args;
521
522 queueOrSendMessage(H.SERVICE_ARGS, s);
523 }
524
525 public final void scheduleStopService(IBinder token) {
526 queueOrSendMessage(H.STOP_SERVICE, token);
527 }
528
529 public final void bindApplication(String processName,
530 ApplicationInfo appInfo, List<ProviderInfo> providers,
531 ComponentName instrumentationName, String profileFile,
532 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700533 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 if (services != null) {
537 // Setup the service cache in the ServiceManager
538 ServiceManager.initServiceCache(services);
539 }
540
541 AppBindData data = new AppBindData();
542 data.processName = processName;
543 data.appInfo = appInfo;
544 data.providers = providers;
545 data.instrumentationName = instrumentationName;
546 data.profileFile = profileFile;
547 data.instrumentationArgs = instrumentationArgs;
548 data.instrumentationWatcher = instrumentationWatcher;
549 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700550 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 data.config = config;
552 queueOrSendMessage(H.BIND_APPLICATION, data);
553 }
554
555 public final void scheduleExit() {
556 queueOrSendMessage(H.EXIT_APPLICATION, null);
557 }
558
Christopher Tate5e1ab332009-09-01 20:32:49 -0700559 public final void scheduleSuicide() {
560 queueOrSendMessage(H.SUICIDE, null);
561 }
562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 public void requestThumbnail(IBinder token) {
564 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
565 }
566
567 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800568 synchronized (mPackages) {
569 if (mPendingConfiguration == null ||
570 mPendingConfiguration.isOtherSeqNewer(config)) {
571 mPendingConfiguration = config;
572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 }
574 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
575 }
576
577 public void updateTimeZone() {
578 TimeZone.setDefault(null);
579 }
580
581 public void processInBackground() {
582 mH.removeMessages(H.GC_WHEN_IDLE);
583 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
584 }
585
586 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
587 DumpServiceInfo data = new DumpServiceInfo();
588 data.fd = fd;
589 data.service = servicetoken;
590 data.args = args;
591 data.dumped = false;
592 queueOrSendMessage(H.DUMP_SERVICE, data);
593 synchronized (data) {
594 while (!data.dumped) {
595 try {
596 data.wait();
597 } catch (InterruptedException e) {
598 // no need to do anything here, we will keep waiting until
599 // dumped is set
600 }
601 }
602 }
603 }
604
605 // This function exists to make sure all receiver dispatching is
606 // correctly ordered, since these are one-way calls and the binder driver
607 // applies transaction ordering per object for such calls.
608 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700609 int resultCode, String dataStr, Bundle extras, boolean ordered,
610 boolean sticky) throws RemoteException {
611 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 }
Bob Leee5408332009-09-04 18:31:17 -0700613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 public void scheduleLowMemory() {
615 queueOrSendMessage(H.LOW_MEMORY, null);
616 }
617
618 public void scheduleActivityConfigurationChanged(IBinder token) {
619 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
620 }
621
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700622 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
623 ProfilerControlData pcd = new ProfilerControlData();
624 pcd.path = path;
625 pcd.fd = fd;
626 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800627 }
628
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700629 public void setSchedulingGroup(int group) {
630 // Note: do this immediately, since going into the foreground
631 // should happen regardless of what pending work we have to do
632 // and the activity manager will wait for us to report back that
633 // we are done before sending us to the background.
634 try {
635 Process.setProcessGroup(Process.myPid(), group);
636 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800637 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700638 }
639 }
Bob Leee5408332009-09-04 18:31:17 -0700640
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700641 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
642 Debug.getMemoryInfo(outInfo);
643 }
Bob Leee5408332009-09-04 18:31:17 -0700644
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700645 public void dispatchPackageBroadcast(int cmd, String[] packages) {
646 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
647 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700648
649 public void scheduleCrash(String msg) {
650 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
651 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 @Override
654 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
655 long nativeMax = Debug.getNativeHeapSize() / 1024;
656 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
657 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
658
659 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
660 Debug.getMemoryInfo(memInfo);
661
662 final int nativeShared = memInfo.nativeSharedDirty;
663 final int dalvikShared = memInfo.dalvikSharedDirty;
664 final int otherShared = memInfo.otherSharedDirty;
665
666 final int nativePrivate = memInfo.nativePrivateDirty;
667 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
668 final int otherPrivate = memInfo.otherPrivateDirty;
669
670 Runtime runtime = Runtime.getRuntime();
671
672 long dalvikMax = runtime.totalMemory() / 1024;
673 long dalvikFree = runtime.freeMemory() / 1024;
674 long dalvikAllocated = dalvikMax - dalvikFree;
675 long viewInstanceCount = ViewDebug.getViewInstanceCount();
676 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Dianne Hackborn21556372010-02-04 16:34:40 -0800677 long appContextInstanceCount = ContextImpl.getInstanceCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 long activityInstanceCount = Activity.getInstanceCount();
679 int globalAssetCount = AssetManager.getGlobalAssetCount();
680 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
681 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
682 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
683 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
684 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
685 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800686 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 // Check to see if we were called by checkin server. If so, print terse format.
689 boolean doCheckinFormat = false;
690 if (args != null) {
691 for (String arg : args) {
692 if ("-c".equals(arg)) doCheckinFormat = true;
693 }
694 }
Bob Leee5408332009-09-04 18:31:17 -0700695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 // For checkin, we print one long comma-separated list of values
697 if (doCheckinFormat) {
698 // NOTE: if you change anything significant below, also consider changing
699 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700700 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 // Header
704 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
705 pw.print(Process.myPid()); pw.print(',');
706 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 // Heap info - max
709 pw.print(nativeMax); pw.print(',');
710 pw.print(dalvikMax); pw.print(',');
711 pw.print("N/A,");
712 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 // Heap info - allocated
715 pw.print(nativeAllocated); pw.print(',');
716 pw.print(dalvikAllocated); pw.print(',');
717 pw.print("N/A,");
718 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 // Heap info - free
721 pw.print(nativeFree); pw.print(',');
722 pw.print(dalvikFree); pw.print(',');
723 pw.print("N/A,");
724 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 // Heap info - proportional set size
727 pw.print(memInfo.nativePss); pw.print(',');
728 pw.print(memInfo.dalvikPss); pw.print(',');
729 pw.print(memInfo.otherPss); pw.print(',');
730 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700733 pw.print(nativeShared); pw.print(',');
734 pw.print(dalvikShared); pw.print(',');
735 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700739 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 pw.print(dalvikPrivate); pw.print(',');
741 pw.print(otherPrivate); pw.print(',');
742 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 // Object counts
745 pw.print(viewInstanceCount); pw.print(',');
746 pw.print(viewRootInstanceCount); pw.print(',');
747 pw.print(appContextInstanceCount); pw.print(',');
748 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 pw.print(globalAssetCount); pw.print(',');
751 pw.print(globalAssetManagerCount); pw.print(',');
752 pw.print(binderLocalObjectCount); pw.print(',');
753 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 pw.print(binderDeathObjectCount); pw.print(',');
756 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 // SQL
759 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800760 pw.print(stats.memoryUsed / 1024); pw.print(',');
761 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
762 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
763 for (int i = 0; i < stats.dbStats.size(); i++) {
764 DbStats dbStats = stats.dbStats.get(i);
765 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
766 dbStats.lookaside, dbStats.dbName);
767 pw.print(',');
768 }
Bob Leee5408332009-09-04 18:31:17 -0700769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 return;
771 }
Bob Leee5408332009-09-04 18:31:17 -0700772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 // otherwise, show human-readable format
774 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
775 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
776 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
777 nativeAllocated + dalvikAllocated);
778 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
779 nativeFree + dalvikFree);
780
781 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
782 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
783
784 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
785 nativeShared + dalvikShared + otherShared);
786 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
787 nativePrivate + dalvikPrivate + otherPrivate);
788
789 pw.println(" ");
790 pw.println(" Objects");
791 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
792 viewRootInstanceCount);
793
794 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
795 "Activities:", activityInstanceCount);
796
797 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
798 "AssetManagers:", globalAssetManagerCount);
799
800 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
801 "Proxy Binders:", binderProxyObjectCount);
802 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
803
804 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 // SQLite mem info
807 pw.println(" ");
808 pw.println(" SQL");
Vasu Noric3849202010-03-09 10:47:25 -0800809 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "memoryUsed:",
810 stats.memoryUsed / 1024);
811 printRow(pw, TWO_COUNT_COLUMNS, "pageCacheOverflo:", stats.pageCacheOverflo / 1024,
812 "largestMemAlloc:", stats.largestMemAlloc / 1024);
813 pw.println(" ");
814 int N = stats.dbStats.size();
815 if (N > 0) {
816 pw.println(" DATABASES");
817 printRow(pw, " %8s %8s %10s %s", "Pagesize", "Dbsize", "Lookaside", "Dbname");
818 for (int i = 0; i < N; i++) {
819 DbStats dbStats = stats.dbStats.get(i);
820 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
821 dbStats.lookaside, dbStats.dbName);
822 }
823 }
Bob Leee5408332009-09-04 18:31:17 -0700824
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700825 // Asset details.
826 String assetAlloc = AssetManager.getAssetAllocations();
827 if (assetAlloc != null) {
828 pw.println(" ");
829 pw.println(" Asset Allocations");
830 pw.print(assetAlloc);
831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833
834 private void printRow(PrintWriter pw, String format, Object...objs) {
835 pw.println(String.format(format, objs));
836 }
837 }
838
839 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -0700840 private H() {
841 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
842 }
843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 public static final int LAUNCH_ACTIVITY = 100;
845 public static final int PAUSE_ACTIVITY = 101;
846 public static final int PAUSE_ACTIVITY_FINISHING= 102;
847 public static final int STOP_ACTIVITY_SHOW = 103;
848 public static final int STOP_ACTIVITY_HIDE = 104;
849 public static final int SHOW_WINDOW = 105;
850 public static final int HIDE_WINDOW = 106;
851 public static final int RESUME_ACTIVITY = 107;
852 public static final int SEND_RESULT = 108;
853 public static final int DESTROY_ACTIVITY = 109;
854 public static final int BIND_APPLICATION = 110;
855 public static final int EXIT_APPLICATION = 111;
856 public static final int NEW_INTENT = 112;
857 public static final int RECEIVER = 113;
858 public static final int CREATE_SERVICE = 114;
859 public static final int SERVICE_ARGS = 115;
860 public static final int STOP_SERVICE = 116;
861 public static final int REQUEST_THUMBNAIL = 117;
862 public static final int CONFIGURATION_CHANGED = 118;
863 public static final int CLEAN_UP_CONTEXT = 119;
864 public static final int GC_WHEN_IDLE = 120;
865 public static final int BIND_SERVICE = 121;
866 public static final int UNBIND_SERVICE = 122;
867 public static final int DUMP_SERVICE = 123;
868 public static final int LOW_MEMORY = 124;
869 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
870 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800871 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700872 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700873 public static final int DESTROY_BACKUP_AGENT = 129;
874 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700875 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800876 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700877 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700878 public static final int SCHEDULE_CRASH = 134;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 String codeToString(int code) {
880 if (localLOGV) {
881 switch (code) {
882 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
883 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
884 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
885 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
886 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
887 case SHOW_WINDOW: return "SHOW_WINDOW";
888 case HIDE_WINDOW: return "HIDE_WINDOW";
889 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
890 case SEND_RESULT: return "SEND_RESULT";
891 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
892 case BIND_APPLICATION: return "BIND_APPLICATION";
893 case EXIT_APPLICATION: return "EXIT_APPLICATION";
894 case NEW_INTENT: return "NEW_INTENT";
895 case RECEIVER: return "RECEIVER";
896 case CREATE_SERVICE: return "CREATE_SERVICE";
897 case SERVICE_ARGS: return "SERVICE_ARGS";
898 case STOP_SERVICE: return "STOP_SERVICE";
899 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
900 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
901 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
902 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
903 case BIND_SERVICE: return "BIND_SERVICE";
904 case UNBIND_SERVICE: return "UNBIND_SERVICE";
905 case DUMP_SERVICE: return "DUMP_SERVICE";
906 case LOW_MEMORY: return "LOW_MEMORY";
907 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
908 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800909 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700910 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
911 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700912 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700913 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800914 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700915 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700916 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
918 }
919 return "(unknown)";
920 }
921 public void handleMessage(Message msg) {
922 switch (msg.what) {
923 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700924 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925
926 r.packageInfo = getPackageInfoNoCheck(
927 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700928 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 } break;
930 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700931 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 handleRelaunchActivity(r, msg.arg1);
933 } break;
934 case PAUSE_ACTIVITY:
935 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700936 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 break;
938 case PAUSE_ACTIVITY_FINISHING:
939 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
940 break;
941 case STOP_ACTIVITY_SHOW:
942 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
943 break;
944 case STOP_ACTIVITY_HIDE:
945 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
946 break;
947 case SHOW_WINDOW:
948 handleWindowVisibility((IBinder)msg.obj, true);
949 break;
950 case HIDE_WINDOW:
951 handleWindowVisibility((IBinder)msg.obj, false);
952 break;
953 case RESUME_ACTIVITY:
954 handleResumeActivity((IBinder)msg.obj, true,
955 msg.arg1 != 0);
956 break;
957 case SEND_RESULT:
958 handleSendResult((ResultData)msg.obj);
959 break;
960 case DESTROY_ACTIVITY:
961 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
962 msg.arg2, false);
963 break;
964 case BIND_APPLICATION:
965 AppBindData data = (AppBindData)msg.obj;
966 handleBindApplication(data);
967 break;
968 case EXIT_APPLICATION:
969 if (mInitialApplication != null) {
970 mInitialApplication.onTerminate();
971 }
972 Looper.myLooper().quit();
973 break;
974 case NEW_INTENT:
975 handleNewIntent((NewIntentData)msg.obj);
976 break;
977 case RECEIVER:
978 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700979 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 break;
981 case CREATE_SERVICE:
982 handleCreateService((CreateServiceData)msg.obj);
983 break;
984 case BIND_SERVICE:
985 handleBindService((BindServiceData)msg.obj);
986 break;
987 case UNBIND_SERVICE:
988 handleUnbindService((BindServiceData)msg.obj);
989 break;
990 case SERVICE_ARGS:
991 handleServiceArgs((ServiceArgsData)msg.obj);
992 break;
993 case STOP_SERVICE:
994 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700995 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 break;
997 case REQUEST_THUMBNAIL:
998 handleRequestThumbnail((IBinder)msg.obj);
999 break;
1000 case CONFIGURATION_CHANGED:
1001 handleConfigurationChanged((Configuration)msg.obj);
1002 break;
1003 case CLEAN_UP_CONTEXT:
1004 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1005 cci.context.performFinalCleanup(cci.who, cci.what);
1006 break;
1007 case GC_WHEN_IDLE:
1008 scheduleGcIdler();
1009 break;
1010 case DUMP_SERVICE:
1011 handleDumpService((DumpServiceInfo)msg.obj);
1012 break;
1013 case LOW_MEMORY:
1014 handleLowMemory();
1015 break;
1016 case ACTIVITY_CONFIGURATION_CHANGED:
1017 handleActivityConfigurationChanged((IBinder)msg.obj);
1018 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001019 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001020 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001021 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001022 case CREATE_BACKUP_AGENT:
1023 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1024 break;
1025 case DESTROY_BACKUP_AGENT:
1026 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1027 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001028 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001029 Process.killProcess(Process.myPid());
1030 break;
1031 case REMOVE_PROVIDER:
1032 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001033 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001034 case ENABLE_JIT:
1035 ensureJitEnabled();
1036 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001037 case DISPATCH_PACKAGE_BROADCAST:
1038 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1039 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001040 case SCHEDULE_CRASH:
1041 throw new RemoteServiceException((String)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043 }
Bob Leee5408332009-09-04 18:31:17 -07001044
1045 void maybeSnapshot() {
1046 if (mBoundApplication != null) {
1047 SamplingProfilerIntegration.writeSnapshot(
1048 mBoundApplication.processName);
1049 }
1050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
1052
1053 private final class Idler implements MessageQueue.IdleHandler {
1054 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001055 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 if (a != null) {
1057 mNewActivities = null;
1058 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001059 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001061 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 TAG, "Reporting idle of " + a +
1063 " finished=" +
1064 (a.activity != null ? a.activity.mFinished : false));
1065 if (a.activity != null && !a.activity.mFinished) {
1066 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001067 am.activityIdle(a.token, a.createdConfig);
1068 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 } catch (RemoteException ex) {
1070 }
1071 }
1072 prev = a;
1073 a = a.nextIdle;
1074 prev.nextIdle = null;
1075 } while (a != null);
1076 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001077 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 return false;
1079 }
1080 }
1081
1082 final class GcIdler implements MessageQueue.IdleHandler {
1083 public final boolean queueIdle() {
1084 doGcIfNeeded();
1085 return false;
1086 }
1087 }
1088
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001089 private final static class ResourcesKey {
1090 final private String mResDir;
1091 final private float mScale;
1092 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001093
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001094 ResourcesKey(String resDir, float scale) {
1095 mResDir = resDir;
1096 mScale = scale;
1097 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1098 }
Bob Leee5408332009-09-04 18:31:17 -07001099
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001100 @Override
1101 public int hashCode() {
1102 return mHash;
1103 }
1104
1105 @Override
1106 public boolean equals(Object obj) {
1107 if (!(obj instanceof ResourcesKey)) {
1108 return false;
1109 }
1110 ResourcesKey peer = (ResourcesKey) obj;
1111 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1112 }
1113 }
1114
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001115 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001116 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001119 public static final String currentPackageName() {
1120 ActivityThread am = currentActivityThread();
1121 return (am != null && am.mBoundApplication != null)
1122 ? am.mBoundApplication.processName : null;
1123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001125 public static final Application currentApplication() {
1126 ActivityThread am = currentActivityThread();
1127 return am != null ? am.mInitialApplication : null;
1128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001130 public static IPackageManager getPackageManager() {
1131 if (sPackageManager != null) {
1132 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1133 return sPackageManager;
1134 }
1135 IBinder b = ServiceManager.getService("package");
1136 //Slog.v("PackageManager", "default service binder = " + b);
1137 sPackageManager = IPackageManager.Stub.asInterface(b);
1138 //Slog.v("PackageManager", "default service = " + sPackageManager);
1139 return sPackageManager;
1140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001142 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1143 if (mDisplayMetrics != null && !forceUpdate) {
1144 return mDisplayMetrics;
1145 }
1146 if (mDisplay == null) {
1147 WindowManager wm = WindowManagerImpl.getDefault();
1148 mDisplay = wm.getDefaultDisplay();
1149 }
1150 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1151 mDisplay.getMetrics(metrics);
1152 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1153 // + metrics.heightPixels + " den=" + metrics.density
1154 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1155 return metrics;
1156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001158 /**
1159 * Creates the top level Resources for applications with the given compatibility info.
1160 *
1161 * @param resDir the resource directory.
1162 * @param compInfo the compability info. It will use the default compatibility info when it's
1163 * null.
1164 */
1165 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1166 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1167 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001169 // Resources is app scale dependent.
1170 if (false) {
1171 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1172 + compInfo.applicationScale);
1173 }
1174 WeakReference<Resources> wr = mActiveResources.get(key);
1175 r = wr != null ? wr.get() : null;
1176 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1177 if (r != null && r.getAssets().isUpToDate()) {
1178 if (false) {
1179 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1180 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1181 }
1182 return r;
1183 }
1184 }
1185
1186 //if (r != null) {
1187 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1188 // + r + " " + resDir);
1189 //}
1190
1191 AssetManager assets = new AssetManager();
1192 if (assets.addAssetPath(resDir) == 0) {
1193 return null;
1194 }
1195
1196 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1197 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1198 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1199 if (false) {
1200 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1201 + r.getConfiguration() + " appScale="
1202 + r.getCompatibilityInfo().applicationScale);
1203 }
1204
1205 synchronized (mPackages) {
1206 WeakReference<Resources> wr = mActiveResources.get(key);
1207 Resources existing = wr != null ? wr.get() : null;
1208 if (existing != null && existing.getAssets().isUpToDate()) {
1209 // Someone else already created the resources while we were
1210 // unlocked; go ahead and use theirs.
1211 r.getAssets().close();
1212 return existing;
1213 }
1214
1215 // XXX need to remove entries when weak references go away
1216 mActiveResources.put(key, new WeakReference<Resources>(r));
1217 return r;
1218 }
1219 }
1220
1221 /**
1222 * Creates the top level resources for the given package.
1223 */
1224 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1225 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1226 }
1227
1228 final Handler getHandler() {
1229 return mH;
1230 }
1231
1232 public final LoadedApk getPackageInfo(String packageName, int flags) {
1233 synchronized (mPackages) {
1234 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1236 ref = mPackages.get(packageName);
1237 } else {
1238 ref = mResourcePackages.get(packageName);
1239 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001240 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001241 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001242 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1243 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 if (packageInfo != null && (packageInfo.mResources == null
1245 || packageInfo.mResources.getAssets().isUpToDate())) {
1246 if (packageInfo.isSecurityViolation()
1247 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1248 throw new SecurityException(
1249 "Requesting code from " + packageName
1250 + " to be run in process "
1251 + mBoundApplication.processName
1252 + "/" + mBoundApplication.appInfo.uid);
1253 }
1254 return packageInfo;
1255 }
1256 }
1257
1258 ApplicationInfo ai = null;
1259 try {
1260 ai = getPackageManager().getApplicationInfo(packageName,
1261 PackageManager.GET_SHARED_LIBRARY_FILES);
1262 } catch (RemoteException e) {
1263 }
1264
1265 if (ai != null) {
1266 return getPackageInfo(ai, flags);
1267 }
1268
1269 return null;
1270 }
1271
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001272 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1274 boolean securityViolation = includeCode && ai.uid != 0
1275 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1276 ? ai.uid != mBoundApplication.appInfo.uid : true);
1277 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1278 |Context.CONTEXT_IGNORE_SECURITY))
1279 == Context.CONTEXT_INCLUDE_CODE) {
1280 if (securityViolation) {
1281 String msg = "Requesting code from " + ai.packageName
1282 + " (with uid " + ai.uid + ")";
1283 if (mBoundApplication != null) {
1284 msg = msg + " to be run in process "
1285 + mBoundApplication.processName + " (with uid "
1286 + mBoundApplication.appInfo.uid + ")";
1287 }
1288 throw new SecurityException(msg);
1289 }
1290 }
1291 return getPackageInfo(ai, null, securityViolation, includeCode);
1292 }
1293
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001294 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 return getPackageInfo(ai, null, false, true);
1296 }
1297
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001298 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1300 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001301 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 if (includeCode) {
1303 ref = mPackages.get(aInfo.packageName);
1304 } else {
1305 ref = mResourcePackages.get(aInfo.packageName);
1306 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001307 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 if (packageInfo == null || (packageInfo.mResources != null
1309 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001310 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 : "Loading resource-only package ") + aInfo.packageName
1312 + " (in " + (mBoundApplication != null
1313 ? mBoundApplication.processName : null)
1314 + ")");
1315 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001316 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 securityViolation, includeCode &&
1318 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1319 if (includeCode) {
1320 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001321 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 } else {
1323 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001324 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
1326 }
1327 return packageInfo;
1328 }
1329 }
1330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 ActivityThread() {
1332 }
1333
1334 public ApplicationThread getApplicationThread()
1335 {
1336 return mAppThread;
1337 }
1338
1339 public Instrumentation getInstrumentation()
1340 {
1341 return mInstrumentation;
1342 }
1343
1344 public Configuration getConfiguration() {
1345 return mConfiguration;
1346 }
1347
1348 public boolean isProfiling() {
1349 return mBoundApplication != null && mBoundApplication.profileFile != null;
1350 }
1351
1352 public String getProfileFilePath() {
1353 return mBoundApplication.profileFile;
1354 }
1355
1356 public Looper getLooper() {
1357 return mLooper;
1358 }
1359
1360 public Application getApplication() {
1361 return mInitialApplication;
1362 }
Bob Leee5408332009-09-04 18:31:17 -07001363
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001364 public String getProcessName() {
1365 return mBoundApplication.processName;
1366 }
Bob Leee5408332009-09-04 18:31:17 -07001367
Dianne Hackborn21556372010-02-04 16:34:40 -08001368 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 synchronized (this) {
1370 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001371 ContextImpl context =
1372 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001373 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 context.init(info, null, this);
1375 context.getResources().updateConfiguration(
1376 getConfiguration(), getDisplayMetricsLocked(false));
1377 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001378 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 // + ": " + context.getResources().getConfiguration());
1380 }
1381 }
1382 return mSystemContext;
1383 }
1384
Mike Cleron432b7132009-09-24 15:28:29 -07001385 public void installSystemApplicationInfo(ApplicationInfo info) {
1386 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001387 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001388 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001389 }
1390 }
1391
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001392 void ensureJitEnabled() {
1393 if (!mJitEnabled) {
1394 mJitEnabled = true;
1395 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1396 }
1397 }
1398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 void scheduleGcIdler() {
1400 if (!mGcIdlerScheduled) {
1401 mGcIdlerScheduled = true;
1402 Looper.myQueue().addIdleHandler(mGcIdler);
1403 }
1404 mH.removeMessages(H.GC_WHEN_IDLE);
1405 }
1406
1407 void unscheduleGcIdler() {
1408 if (mGcIdlerScheduled) {
1409 mGcIdlerScheduled = false;
1410 Looper.myQueue().removeIdleHandler(mGcIdler);
1411 }
1412 mH.removeMessages(H.GC_WHEN_IDLE);
1413 }
1414
1415 void doGcIfNeeded() {
1416 mGcIdlerScheduled = false;
1417 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001418 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 // + "m now=" + now);
1420 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001421 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 BinderInternal.forceGc("bg");
1423 }
1424 }
1425
1426 public final ActivityInfo resolveActivityInfo(Intent intent) {
1427 ActivityInfo aInfo = intent.resolveActivityInfo(
1428 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1429 if (aInfo == null) {
1430 // Throw an exception.
1431 Instrumentation.checkStartActivityResult(
1432 IActivityManager.START_CLASS_NOT_FOUND, intent);
1433 }
1434 return aInfo;
1435 }
Bob Leee5408332009-09-04 18:31:17 -07001436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
1439 Object lastNonConfigurationInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001440 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001442 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 r.intent = intent;
1444 r.state = state;
1445 r.parent = parent;
1446 r.embeddedID = id;
1447 r.activityInfo = activityInfo;
1448 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
1449 if (localLOGV) {
1450 ComponentName compname = intent.getComponent();
1451 String name;
1452 if (compname != null) {
1453 name = compname.toShortString();
1454 } else {
1455 name = "(Intent " + intent + ").getComponent() returned null";
1456 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001457 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 + ", comp=" + name
1459 + ", token=" + token);
1460 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001461 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 }
1463
1464 public final Activity getActivity(IBinder token) {
1465 return mActivities.get(token).activity;
1466 }
1467
1468 public final void sendActivityResult(
1469 IBinder token, String id, int requestCode,
1470 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001471 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001472 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1474 list.add(new ResultInfo(id, requestCode, resultCode, data));
1475 mAppThread.scheduleSendResult(token, list);
1476 }
1477
1478 // if the thread hasn't started yet, we don't have the handler, so just
1479 // save the messages until we're ready.
1480 private final void queueOrSendMessage(int what, Object obj) {
1481 queueOrSendMessage(what, obj, 0, 0);
1482 }
1483
1484 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1485 queueOrSendMessage(what, obj, arg1, 0);
1486 }
1487
1488 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1489 synchronized (this) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001490 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1492 + ": " + arg1 + " / " + obj);
1493 Message msg = Message.obtain();
1494 msg.what = what;
1495 msg.obj = obj;
1496 msg.arg1 = arg1;
1497 msg.arg2 = arg2;
1498 mH.sendMessage(msg);
1499 }
1500 }
1501
Dianne Hackborn21556372010-02-04 16:34:40 -08001502 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 String what) {
1504 ContextCleanupInfo cci = new ContextCleanupInfo();
1505 cci.context = context;
1506 cci.who = who;
1507 cci.what = what;
1508 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1509 }
1510
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001511 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1513
1514 ActivityInfo aInfo = r.activityInfo;
1515 if (r.packageInfo == null) {
1516 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1517 Context.CONTEXT_INCLUDE_CODE);
1518 }
Bob Leee5408332009-09-04 18:31:17 -07001519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 ComponentName component = r.intent.getComponent();
1521 if (component == null) {
1522 component = r.intent.resolveActivity(
1523 mInitialApplication.getPackageManager());
1524 r.intent.setComponent(component);
1525 }
1526
1527 if (r.activityInfo.targetActivity != null) {
1528 component = new ComponentName(r.activityInfo.packageName,
1529 r.activityInfo.targetActivity);
1530 }
1531
1532 Activity activity = null;
1533 try {
1534 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1535 activity = mInstrumentation.newActivity(
1536 cl, component.getClassName(), r.intent);
1537 r.intent.setExtrasClassLoader(cl);
1538 if (r.state != null) {
1539 r.state.setClassLoader(cl);
1540 }
1541 } catch (Exception e) {
1542 if (!mInstrumentation.onException(activity, e)) {
1543 throw new RuntimeException(
1544 "Unable to instantiate activity " + component
1545 + ": " + e.toString(), e);
1546 }
1547 }
1548
1549 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001550 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001551
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001552 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1553 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 TAG, r + ": app=" + app
1555 + ", appName=" + app.getPackageName()
1556 + ", pkg=" + r.packageInfo.getPackageName()
1557 + ", comp=" + r.intent.getComponent().toShortString()
1558 + ", dir=" + r.packageInfo.getAppDir());
1559
1560 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001561 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 appContext.init(r.packageInfo, r.token, this);
1563 appContext.setOuterContext(activity);
1564 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1565 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001566 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001567 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001568 activity.attach(appContext, this, getInstrumentation(), r.token,
1569 r.ident, app, r.intent, r.activityInfo, title, r.parent,
1570 r.embeddedID, r.lastNonConfigurationInstance,
1571 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001572
Christopher Tateb70f3df2009-04-07 16:07:59 -07001573 if (customIntent != null) {
1574 activity.mIntent = customIntent;
1575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 r.lastNonConfigurationInstance = null;
1577 r.lastNonConfigurationChildInstances = null;
1578 activity.mStartedActivity = false;
1579 int theme = r.activityInfo.getThemeResource();
1580 if (theme != 0) {
1581 activity.setTheme(theme);
1582 }
1583
1584 activity.mCalled = false;
1585 mInstrumentation.callActivityOnCreate(activity, r.state);
1586 if (!activity.mCalled) {
1587 throw new SuperNotCalledException(
1588 "Activity " + r.intent.getComponent().toShortString() +
1589 " did not call through to super.onCreate()");
1590 }
1591 r.activity = activity;
1592 r.stopped = true;
1593 if (!r.activity.mFinished) {
1594 activity.performStart();
1595 r.stopped = false;
1596 }
1597 if (!r.activity.mFinished) {
1598 if (r.state != null) {
1599 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1600 }
1601 }
1602 if (!r.activity.mFinished) {
1603 activity.mCalled = false;
1604 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1605 if (!activity.mCalled) {
1606 throw new SuperNotCalledException(
1607 "Activity " + r.intent.getComponent().toShortString() +
1608 " did not call through to super.onPostCreate()");
1609 }
1610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612 r.paused = true;
1613
1614 mActivities.put(r.token, r);
1615
1616 } catch (SuperNotCalledException e) {
1617 throw e;
1618
1619 } catch (Exception e) {
1620 if (!mInstrumentation.onException(activity, e)) {
1621 throw new RuntimeException(
1622 "Unable to start activity " + component
1623 + ": " + e.toString(), e);
1624 }
1625 }
1626
1627 return activity;
1628 }
1629
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001630 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 // If we are getting ready to gc after going to the background, well
1632 // we are back active so skip it.
1633 unscheduleGcIdler();
1634
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001635 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001637 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638
1639 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001640 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001641 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 handleResumeActivity(r.token, false, r.isForward);
1643
1644 if (!r.activity.mFinished && r.startsNotResumed) {
1645 // The activity manager actually wants this one to start out
1646 // paused, because it needs to be visible but isn't in the
1647 // foreground. We accomplish this by going through the
1648 // normal startup (because activities expect to go through
1649 // onResume() the first time they run, before their window
1650 // is displayed), and then pausing it. However, in this case
1651 // we do -not- need to do the full pause cycle (of freezing
1652 // and such) because the activity manager assumes it can just
1653 // retain the current state it has.
1654 try {
1655 r.activity.mCalled = false;
1656 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001657 // We need to keep around the original state, in case
1658 // we need to be created again.
1659 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 if (!r.activity.mCalled) {
1661 throw new SuperNotCalledException(
1662 "Activity " + r.intent.getComponent().toShortString() +
1663 " did not call through to super.onPause()");
1664 }
1665
1666 } catch (SuperNotCalledException e) {
1667 throw e;
1668
1669 } catch (Exception e) {
1670 if (!mInstrumentation.onException(r.activity, e)) {
1671 throw new RuntimeException(
1672 "Unable to pause activity "
1673 + r.intent.getComponent().toShortString()
1674 + ": " + e.toString(), e);
1675 }
1676 }
1677 r.paused = true;
1678 }
1679 } else {
1680 // If there was an error, for any reason, tell the activity
1681 // manager to stop us.
1682 try {
1683 ActivityManagerNative.getDefault()
1684 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1685 } catch (RemoteException ex) {
1686 }
1687 }
1688 }
1689
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001690 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 List<Intent> intents) {
1692 final int N = intents.size();
1693 for (int i=0; i<N; i++) {
1694 Intent intent = intents.get(i);
1695 intent.setExtrasClassLoader(r.activity.getClassLoader());
1696 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1697 }
1698 }
1699
1700 public final void performNewIntents(IBinder token,
1701 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001702 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 if (r != null) {
1704 final boolean resumed = !r.paused;
1705 if (resumed) {
1706 mInstrumentation.callActivityOnPause(r.activity);
1707 }
1708 deliverNewIntents(r, intents);
1709 if (resumed) {
1710 mInstrumentation.callActivityOnResume(r.activity);
1711 }
1712 }
1713 }
Bob Leee5408332009-09-04 18:31:17 -07001714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 private final void handleNewIntent(NewIntentData data) {
1716 performNewIntents(data.token, data.intents);
1717 }
1718
1719 private final void handleReceiver(ReceiverData data) {
1720 // If we are getting ready to gc after going to the background, well
1721 // we are back active so skip it.
1722 unscheduleGcIdler();
1723
1724 String component = data.intent.getComponent().getClassName();
1725
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001726 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 data.info.applicationInfo);
1728
1729 IActivityManager mgr = ActivityManagerNative.getDefault();
1730
1731 BroadcastReceiver receiver = null;
1732 try {
1733 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1734 data.intent.setExtrasClassLoader(cl);
1735 if (data.resultExtras != null) {
1736 data.resultExtras.setClassLoader(cl);
1737 }
1738 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1739 } catch (Exception e) {
1740 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001741 if (DEBUG_BROADCAST) Slog.i(TAG,
1742 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1744 data.resultData, data.resultExtras, data.resultAbort);
1745 } catch (RemoteException ex) {
1746 }
1747 throw new RuntimeException(
1748 "Unable to instantiate receiver " + component
1749 + ": " + e.toString(), e);
1750 }
1751
1752 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001753 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001754
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001755 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 TAG, "Performing receive of " + data.intent
1757 + ": app=" + app
1758 + ", appName=" + app.getPackageName()
1759 + ", pkg=" + packageInfo.getPackageName()
1760 + ", comp=" + data.intent.getComponent().toShortString()
1761 + ", dir=" + packageInfo.getAppDir());
1762
Dianne Hackborn21556372010-02-04 16:34:40 -08001763 ContextImpl context = (ContextImpl)app.getBaseContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 receiver.setOrderedHint(true);
1765 receiver.setResult(data.resultCode, data.resultData,
1766 data.resultExtras);
1767 receiver.setOrderedHint(data.sync);
1768 receiver.onReceive(context.getReceiverRestrictedContext(),
1769 data.intent);
1770 } catch (Exception e) {
1771 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001772 if (DEBUG_BROADCAST) Slog.i(TAG,
1773 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1775 data.resultData, data.resultExtras, data.resultAbort);
1776 } catch (RemoteException ex) {
1777 }
1778 if (!mInstrumentation.onException(receiver, e)) {
1779 throw new RuntimeException(
1780 "Unable to start receiver " + component
1781 + ": " + e.toString(), e);
1782 }
1783 }
1784
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001785 QueuedWork.waitToFinish();
1786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 try {
1788 if (data.sync) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001789 if (DEBUG_BROADCAST) Slog.i(TAG,
1790 "Finishing ordered broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 mgr.finishReceiver(
1792 mAppThread.asBinder(), receiver.getResultCode(),
1793 receiver.getResultData(), receiver.getResultExtras(false),
1794 receiver.getAbortBroadcast());
1795 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001796 if (DEBUG_BROADCAST) Slog.i(TAG,
1797 "Finishing broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
1799 }
1800 } catch (RemoteException ex) {
1801 }
1802 }
1803
Christopher Tate181fafa2009-05-14 11:12:14 -07001804 // Instantiate a BackupAgent and tell it that it's alive
1805 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001806 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001807
1808 // no longer idle; we have backup work to do
1809 unscheduleGcIdler();
1810
1811 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001812 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001813 String packageName = packageInfo.mPackageName;
1814 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001815 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001816 + " already exists");
1817 return;
1818 }
Bob Leee5408332009-09-04 18:31:17 -07001819
Christopher Tate181fafa2009-05-14 11:12:14 -07001820 BackupAgent agent = null;
1821 String classname = data.appInfo.backupAgentName;
1822 if (classname == null) {
1823 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001824 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001825 + packageName);
1826 return;
1827 }
1828 classname = "android.app.FullBackupAgent";
1829 }
1830 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001831 IBinder binder = null;
1832 try {
1833 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1834 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1835
1836 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001837 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001838 + data.appInfo.backupAgentName);
1839
Dianne Hackborn21556372010-02-04 16:34:40 -08001840 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001841 context.init(packageInfo, null, this);
1842 context.setOuterContext(agent);
1843 agent.attach(context);
1844
1845 agent.onCreate();
1846 binder = agent.onBind();
1847 mBackupAgents.put(packageName, agent);
1848 } catch (Exception e) {
1849 // If this is during restore, fail silently; otherwise go
1850 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001851 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001852 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1853 throw e;
1854 }
1855 // falling through with 'binder' still null
1856 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001857
1858 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001859 try {
1860 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1861 } catch (RemoteException e) {
1862 // nothing to do.
1863 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001864 } catch (Exception e) {
1865 throw new RuntimeException("Unable to create BackupAgent "
1866 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1867 }
1868 }
1869
1870 // Tear down a BackupAgent
1871 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001872 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001873
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001874 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001875 String packageName = packageInfo.mPackageName;
1876 BackupAgent agent = mBackupAgents.get(packageName);
1877 if (agent != null) {
1878 try {
1879 agent.onDestroy();
1880 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001881 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001882 e.printStackTrace();
1883 }
1884 mBackupAgents.remove(packageName);
1885 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001886 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001887 }
1888 }
1889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 private final void handleCreateService(CreateServiceData data) {
1891 // If we are getting ready to gc after going to the background, well
1892 // we are back active so skip it.
1893 unscheduleGcIdler();
1894
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001895 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 data.info.applicationInfo);
1897 Service service = null;
1898 try {
1899 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1900 service = (Service) cl.loadClass(data.info.name).newInstance();
1901 } catch (Exception e) {
1902 if (!mInstrumentation.onException(service, e)) {
1903 throw new RuntimeException(
1904 "Unable to instantiate service " + data.info.name
1905 + ": " + e.toString(), e);
1906 }
1907 }
1908
1909 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001910 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911
Dianne Hackborn21556372010-02-04 16:34:40 -08001912 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 context.init(packageInfo, null, this);
1914
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001915 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 context.setOuterContext(service);
1917 service.attach(context, this, data.info.name, data.token, app,
1918 ActivityManagerNative.getDefault());
1919 service.onCreate();
1920 mServices.put(data.token, service);
1921 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001922 ActivityManagerNative.getDefault().serviceDoneExecuting(
1923 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 } catch (RemoteException e) {
1925 // nothing to do.
1926 }
1927 } catch (Exception e) {
1928 if (!mInstrumentation.onException(service, e)) {
1929 throw new RuntimeException(
1930 "Unable to create service " + data.info.name
1931 + ": " + e.toString(), e);
1932 }
1933 }
1934 }
1935
1936 private final void handleBindService(BindServiceData data) {
1937 Service s = mServices.get(data.token);
1938 if (s != null) {
1939 try {
1940 data.intent.setExtrasClassLoader(s.getClassLoader());
1941 try {
1942 if (!data.rebind) {
1943 IBinder binder = s.onBind(data.intent);
1944 ActivityManagerNative.getDefault().publishService(
1945 data.token, data.intent, binder);
1946 } else {
1947 s.onRebind(data.intent);
1948 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001949 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001951 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 } catch (RemoteException ex) {
1953 }
1954 } catch (Exception e) {
1955 if (!mInstrumentation.onException(s, e)) {
1956 throw new RuntimeException(
1957 "Unable to bind to service " + s
1958 + " with " + data.intent + ": " + e.toString(), e);
1959 }
1960 }
1961 }
1962 }
1963
1964 private final void handleUnbindService(BindServiceData data) {
1965 Service s = mServices.get(data.token);
1966 if (s != null) {
1967 try {
1968 data.intent.setExtrasClassLoader(s.getClassLoader());
1969 boolean doRebind = s.onUnbind(data.intent);
1970 try {
1971 if (doRebind) {
1972 ActivityManagerNative.getDefault().unbindFinished(
1973 data.token, data.intent, doRebind);
1974 } else {
1975 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001976 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
1978 } catch (RemoteException ex) {
1979 }
1980 } catch (Exception e) {
1981 if (!mInstrumentation.onException(s, e)) {
1982 throw new RuntimeException(
1983 "Unable to unbind to service " + s
1984 + " with " + data.intent + ": " + e.toString(), e);
1985 }
1986 }
1987 }
1988 }
1989
1990 private void handleDumpService(DumpServiceInfo info) {
1991 try {
1992 Service s = mServices.get(info.service);
1993 if (s != null) {
1994 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
1995 s.dump(info.fd, pw, info.args);
1996 pw.close();
1997 }
1998 } finally {
1999 synchronized (info) {
2000 info.dumped = true;
2001 info.notifyAll();
2002 }
2003 }
2004 }
2005
2006 private final void handleServiceArgs(ServiceArgsData data) {
2007 Service s = mServices.get(data.token);
2008 if (s != null) {
2009 try {
2010 if (data.args != null) {
2011 data.args.setExtrasClassLoader(s.getClassLoader());
2012 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002013 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002014
2015 QueuedWork.waitToFinish();
2016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002018 ActivityManagerNative.getDefault().serviceDoneExecuting(
2019 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 } catch (RemoteException e) {
2021 // nothing to do.
2022 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002023 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 } catch (Exception e) {
2025 if (!mInstrumentation.onException(s, e)) {
2026 throw new RuntimeException(
2027 "Unable to start service " + s
2028 + " with " + data.args + ": " + e.toString(), e);
2029 }
2030 }
2031 }
2032 }
2033
2034 private final void handleStopService(IBinder token) {
2035 Service s = mServices.remove(token);
2036 if (s != null) {
2037 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002038 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 s.onDestroy();
2040 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002041 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002043 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002045
2046 QueuedWork.waitToFinish();
2047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002049 ActivityManagerNative.getDefault().serviceDoneExecuting(
2050 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 } catch (RemoteException e) {
2052 // nothing to do.
2053 }
2054 } catch (Exception e) {
2055 if (!mInstrumentation.onException(s, e)) {
2056 throw new RuntimeException(
2057 "Unable to stop service " + s
2058 + ": " + e.toString(), e);
2059 }
2060 }
2061 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002062 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
2064
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002065 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002067 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002068 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 + " finished=" + r.activity.mFinished);
2070 if (r != null && !r.activity.mFinished) {
2071 if (clearHide) {
2072 r.hideForNow = false;
2073 r.activity.mStartedActivity = false;
2074 }
2075 try {
2076 if (r.pendingIntents != null) {
2077 deliverNewIntents(r, r.pendingIntents);
2078 r.pendingIntents = null;
2079 }
2080 if (r.pendingResults != null) {
2081 deliverResults(r, r.pendingResults);
2082 r.pendingResults = null;
2083 }
2084 r.activity.performResume();
2085
Bob Leee5408332009-09-04 18:31:17 -07002086 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 r.paused = false;
2090 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 r.state = null;
2092 } catch (Exception e) {
2093 if (!mInstrumentation.onException(r.activity, e)) {
2094 throw new RuntimeException(
2095 "Unable to resume activity "
2096 + r.intent.getComponent().toShortString()
2097 + ": " + e.toString(), e);
2098 }
2099 }
2100 }
2101 return r;
2102 }
2103
2104 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2105 // If we are getting ready to gc after going to the background, well
2106 // we are back active so skip it.
2107 unscheduleGcIdler();
2108
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002109 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110
2111 if (r != null) {
2112 final Activity a = r.activity;
2113
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002114 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 TAG, "Resume " + r + " started activity: " +
2116 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2117 + ", finished: " + a.mFinished);
2118
2119 final int forwardBit = isForward ?
2120 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 // If the window hasn't yet been added to the window manager,
2123 // and this guy didn't finish itself or start another activity,
2124 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002125 boolean willBeVisible = !a.mStartedActivity;
2126 if (!willBeVisible) {
2127 try {
2128 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2129 a.getActivityToken());
2130 } catch (RemoteException e) {
2131 }
2132 }
2133 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 r.window = r.activity.getWindow();
2135 View decor = r.window.getDecorView();
2136 decor.setVisibility(View.INVISIBLE);
2137 ViewManager wm = a.getWindowManager();
2138 WindowManager.LayoutParams l = r.window.getAttributes();
2139 a.mDecor = decor;
2140 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2141 l.softInputMode |= forwardBit;
2142 if (a.mVisibleFromClient) {
2143 a.mWindowAdded = true;
2144 wm.addView(decor, l);
2145 }
2146
2147 // If the window has already been added, but during resume
2148 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002149 // window visible.
2150 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002151 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 TAG, "Launch " + r + " mStartedActivity set");
2153 r.hideForNow = true;
2154 }
2155
2156 // The window is now visible if it has been added, we are not
2157 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002158 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002159 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002161 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002162 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 performConfigurationChanged(r.activity, r.newConfig);
2164 r.newConfig = null;
2165 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002166 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 + isForward);
2168 WindowManager.LayoutParams l = r.window.getAttributes();
2169 if ((l.softInputMode
2170 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2171 != forwardBit) {
2172 l.softInputMode = (l.softInputMode
2173 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2174 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002175 if (r.activity.mVisibleFromClient) {
2176 ViewManager wm = a.getWindowManager();
2177 View decor = r.window.getDecorView();
2178 wm.updateViewLayout(decor, l);
2179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 }
2181 r.activity.mVisibleFromServer = true;
2182 mNumVisibleActivities++;
2183 if (r.activity.mVisibleFromClient) {
2184 r.activity.makeVisible();
2185 }
2186 }
2187
2188 r.nextIdle = mNewActivities;
2189 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002190 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 TAG, "Scheduling idle handler for " + r);
2192 Looper.myQueue().addIdleHandler(new Idler());
2193
2194 } else {
2195 // If an exception was thrown when trying to resume, then
2196 // just end this activity.
2197 try {
2198 ActivityManagerNative.getDefault()
2199 .finishActivity(token, Activity.RESULT_CANCELED, null);
2200 } catch (RemoteException ex) {
2201 }
2202 }
2203 }
2204
2205 private int mThumbnailWidth = -1;
2206 private int mThumbnailHeight = -1;
2207
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002208 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 Bitmap thumbnail = null;
2210 try {
2211 int w = mThumbnailWidth;
2212 int h;
2213 if (w < 0) {
2214 Resources res = r.activity.getResources();
2215 mThumbnailHeight = h =
2216 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2217
2218 mThumbnailWidth = w =
2219 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2220 } else {
2221 h = mThumbnailHeight;
2222 }
2223
Jim Miller0b2a6d02010-07-13 18:01:29 -07002224 // On platforms where we don't want thumbnails, set dims to (0,0)
2225 if ((w > 0) && (h > 0)) {
2226 View topView = r.activity.getWindow().getDecorView();
2227
2228 // Maximize bitmap by capturing in native aspect.
2229 if (topView.getWidth() >= topView.getHeight()) {
2230 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2231 } else {
2232 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2233 }
2234
2235 thumbnail.eraseColor(0);
2236 Canvas cv = new Canvas(thumbnail);
2237 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2238 thumbnail = null;
2239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 } catch (Exception e) {
2243 if (!mInstrumentation.onException(r.activity, e)) {
2244 throw new RuntimeException(
2245 "Unable to create thumbnail of "
2246 + r.intent.getComponent().toShortString()
2247 + ": " + e.toString(), e);
2248 }
2249 thumbnail = null;
2250 }
2251
2252 return thumbnail;
2253 }
2254
2255 private final void handlePauseActivity(IBinder token, boolean finished,
2256 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002257 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002259 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 if (userLeaving) {
2261 performUserLeavingActivity(r);
2262 }
Bob Leee5408332009-09-04 18:31:17 -07002263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 r.activity.mConfigChangeFlags |= configChanges;
2265 Bundle state = performPauseActivity(token, finished, true);
2266
2267 // Tell the activity manager we have paused.
2268 try {
2269 ActivityManagerNative.getDefault().activityPaused(token, state);
2270 } catch (RemoteException ex) {
2271 }
2272 }
2273 }
2274
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002275 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 mInstrumentation.callActivityOnUserLeaving(r.activity);
2277 }
2278
2279 final Bundle performPauseActivity(IBinder token, boolean finished,
2280 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002281 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 return r != null ? performPauseActivity(r, finished, saveState) : null;
2283 }
2284
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002285 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 boolean saveState) {
2287 if (r.paused) {
2288 if (r.activity.mFinished) {
2289 // If we are finishing, we won't call onResume() in certain cases.
2290 // So here we likewise don't want to call onPause() if the activity
2291 // isn't resumed.
2292 return null;
2293 }
2294 RuntimeException e = new RuntimeException(
2295 "Performing pause of activity that is not resumed: "
2296 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002297 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 }
2299 Bundle state = null;
2300 if (finished) {
2301 r.activity.mFinished = true;
2302 }
2303 try {
2304 // Next have the activity save its current state and managed dialogs...
2305 if (!r.activity.mFinished && saveState) {
2306 state = new Bundle();
2307 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2308 r.state = state;
2309 }
2310 // Now we are idle.
2311 r.activity.mCalled = false;
2312 mInstrumentation.callActivityOnPause(r.activity);
2313 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2314 if (!r.activity.mCalled) {
2315 throw new SuperNotCalledException(
2316 "Activity " + r.intent.getComponent().toShortString() +
2317 " did not call through to super.onPause()");
2318 }
2319
2320 } catch (SuperNotCalledException e) {
2321 throw e;
2322
2323 } catch (Exception e) {
2324 if (!mInstrumentation.onException(r.activity, e)) {
2325 throw new RuntimeException(
2326 "Unable to pause activity "
2327 + r.intent.getComponent().toShortString()
2328 + ": " + e.toString(), e);
2329 }
2330 }
2331 r.paused = true;
2332 return state;
2333 }
2334
2335 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002336 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 performStopActivityInner(r, null, false);
2338 }
2339
2340 private static class StopInfo {
2341 Bitmap thumbnail;
2342 CharSequence description;
2343 }
2344
2345 private final class ProviderRefCount {
2346 public int count;
2347 ProviderRefCount(int pCount) {
2348 count = pCount;
2349 }
2350 }
2351
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002352 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002354 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 if (r != null) {
2356 if (!keepShown && r.stopped) {
2357 if (r.activity.mFinished) {
2358 // If we are finishing, we won't call onResume() in certain
2359 // cases. So here we likewise don't want to call onStop()
2360 // if the activity isn't resumed.
2361 return;
2362 }
2363 RuntimeException e = new RuntimeException(
2364 "Performing stop of activity that is not resumed: "
2365 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002366 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 }
2368
2369 if (info != null) {
2370 try {
2371 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002372 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 info.description = r.activity.onCreateDescription();
2374 } catch (Exception e) {
2375 if (!mInstrumentation.onException(r.activity, e)) {
2376 throw new RuntimeException(
2377 "Unable to save state of activity "
2378 + r.intent.getComponent().toShortString()
2379 + ": " + e.toString(), e);
2380 }
2381 }
2382 }
2383
2384 if (!keepShown) {
2385 try {
2386 // Now we are idle.
2387 r.activity.performStop();
2388 } catch (Exception e) {
2389 if (!mInstrumentation.onException(r.activity, e)) {
2390 throw new RuntimeException(
2391 "Unable to stop activity "
2392 + r.intent.getComponent().toShortString()
2393 + ": " + e.toString(), e);
2394 }
2395 }
2396 r.stopped = true;
2397 }
2398
2399 r.paused = true;
2400 }
2401 }
2402
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002403 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 View v = r.activity.mDecor;
2405 if (v != null) {
2406 if (show) {
2407 if (!r.activity.mVisibleFromServer) {
2408 r.activity.mVisibleFromServer = true;
2409 mNumVisibleActivities++;
2410 if (r.activity.mVisibleFromClient) {
2411 r.activity.makeVisible();
2412 }
2413 }
2414 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002415 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002416 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 performConfigurationChanged(r.activity, r.newConfig);
2418 r.newConfig = null;
2419 }
2420 } else {
2421 if (r.activity.mVisibleFromServer) {
2422 r.activity.mVisibleFromServer = false;
2423 mNumVisibleActivities--;
2424 v.setVisibility(View.INVISIBLE);
2425 }
2426 }
2427 }
2428 }
2429
2430 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002431 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 r.activity.mConfigChangeFlags |= configChanges;
2433
2434 StopInfo info = new StopInfo();
2435 performStopActivityInner(r, info, show);
2436
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002437 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 TAG, "Finishing stop of " + r + ": show=" + show
2439 + " win=" + r.window);
2440
2441 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 // Tell activity manager we have been stopped.
2444 try {
2445 ActivityManagerNative.getDefault().activityStopped(
2446 r.token, info.thumbnail, info.description);
2447 } catch (RemoteException ex) {
2448 }
2449 }
2450
2451 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002452 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 if (r.stopped) {
2454 r.activity.performRestart();
2455 r.stopped = false;
2456 }
2457 }
2458
2459 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002460 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 if (!show && !r.stopped) {
2462 performStopActivityInner(r, null, show);
2463 } else if (show && r.stopped) {
2464 // If we are getting ready to gc after going to the background, well
2465 // we are back active so skip it.
2466 unscheduleGcIdler();
2467
2468 r.activity.performRestart();
2469 r.stopped = false;
2470 }
2471 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002472 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 TAG, "Handle window " + r + " visibility: " + show);
2474 updateVisibility(r, show);
2475 }
2476 }
2477
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002478 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 final int N = results.size();
2480 for (int i=0; i<N; i++) {
2481 ResultInfo ri = results.get(i);
2482 try {
2483 if (ri.mData != null) {
2484 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2485 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002486 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002487 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 r.activity.dispatchActivityResult(ri.mResultWho,
2489 ri.mRequestCode, ri.mResultCode, ri.mData);
2490 } catch (Exception e) {
2491 if (!mInstrumentation.onException(r.activity, e)) {
2492 throw new RuntimeException(
2493 "Failure delivering result " + ri + " to activity "
2494 + r.intent.getComponent().toShortString()
2495 + ": " + e.toString(), e);
2496 }
2497 }
2498 }
2499 }
2500
2501 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002502 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002503 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 if (r != null) {
2505 final boolean resumed = !r.paused;
2506 if (!r.activity.mFinished && r.activity.mDecor != null
2507 && r.hideForNow && resumed) {
2508 // We had hidden the activity because it started another
2509 // one... we have gotten a result back and we are not
2510 // paused, so make sure our window is visible.
2511 updateVisibility(r, true);
2512 }
2513 if (resumed) {
2514 try {
2515 // Now we are idle.
2516 r.activity.mCalled = false;
2517 mInstrumentation.callActivityOnPause(r.activity);
2518 if (!r.activity.mCalled) {
2519 throw new SuperNotCalledException(
2520 "Activity " + r.intent.getComponent().toShortString()
2521 + " did not call through to super.onPause()");
2522 }
2523 } catch (SuperNotCalledException e) {
2524 throw e;
2525 } catch (Exception e) {
2526 if (!mInstrumentation.onException(r.activity, e)) {
2527 throw new RuntimeException(
2528 "Unable to pause activity "
2529 + r.intent.getComponent().toShortString()
2530 + ": " + e.toString(), e);
2531 }
2532 }
2533 }
2534 deliverResults(r, res.results);
2535 if (resumed) {
2536 mInstrumentation.callActivityOnResume(r.activity);
2537 }
2538 }
2539 }
2540
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002541 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 return performDestroyActivity(token, finishing, 0, false);
2543 }
2544
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002545 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002547 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002548 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 if (r != null) {
2550 r.activity.mConfigChangeFlags |= configChanges;
2551 if (finishing) {
2552 r.activity.mFinished = true;
2553 }
2554 if (!r.paused) {
2555 try {
2556 r.activity.mCalled = false;
2557 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002558 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 r.activity.getComponentName().getClassName());
2560 if (!r.activity.mCalled) {
2561 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002562 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 + " did not call through to super.onPause()");
2564 }
2565 } catch (SuperNotCalledException e) {
2566 throw e;
2567 } catch (Exception e) {
2568 if (!mInstrumentation.onException(r.activity, e)) {
2569 throw new RuntimeException(
2570 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002571 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 + ": " + e.toString(), e);
2573 }
2574 }
2575 r.paused = true;
2576 }
2577 if (!r.stopped) {
2578 try {
2579 r.activity.performStop();
2580 } catch (SuperNotCalledException e) {
2581 throw e;
2582 } catch (Exception e) {
2583 if (!mInstrumentation.onException(r.activity, e)) {
2584 throw new RuntimeException(
2585 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002586 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 + ": " + e.toString(), e);
2588 }
2589 }
2590 r.stopped = true;
2591 }
2592 if (getNonConfigInstance) {
2593 try {
2594 r.lastNonConfigurationInstance
2595 = r.activity.onRetainNonConfigurationInstance();
2596 } catch (Exception e) {
2597 if (!mInstrumentation.onException(r.activity, e)) {
2598 throw new RuntimeException(
2599 "Unable to retain activity "
2600 + r.intent.getComponent().toShortString()
2601 + ": " + e.toString(), e);
2602 }
2603 }
2604 try {
2605 r.lastNonConfigurationChildInstances
2606 = r.activity.onRetainNonConfigurationChildInstances();
2607 } catch (Exception e) {
2608 if (!mInstrumentation.onException(r.activity, e)) {
2609 throw new RuntimeException(
2610 "Unable to retain child activities "
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 }
Bob Leee5408332009-09-04 18:31:17 -07002615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 }
2617 try {
2618 r.activity.mCalled = false;
2619 r.activity.onDestroy();
2620 if (!r.activity.mCalled) {
2621 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002622 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 " did not call through to super.onDestroy()");
2624 }
2625 if (r.window != null) {
2626 r.window.closeAllPanels();
2627 }
2628 } catch (SuperNotCalledException e) {
2629 throw e;
2630 } catch (Exception e) {
2631 if (!mInstrumentation.onException(r.activity, e)) {
2632 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002633 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2634 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 }
2636 }
2637 }
2638 mActivities.remove(token);
2639
2640 return r;
2641 }
2642
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002643 private static String safeToComponentShortString(Intent intent) {
2644 ComponentName component = intent.getComponent();
2645 return component == null ? "[Unknown]" : component.toShortString();
2646 }
2647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 private final void handleDestroyActivity(IBinder token, boolean finishing,
2649 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002650 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 configChanges, getNonConfigInstance);
2652 if (r != null) {
2653 WindowManager wm = r.activity.getWindowManager();
2654 View v = r.activity.mDecor;
2655 if (v != null) {
2656 if (r.activity.mVisibleFromServer) {
2657 mNumVisibleActivities--;
2658 }
2659 IBinder wtoken = v.getWindowToken();
2660 if (r.activity.mWindowAdded) {
2661 wm.removeViewImmediate(v);
2662 }
2663 if (wtoken != null) {
2664 WindowManagerImpl.getDefault().closeAll(wtoken,
2665 r.activity.getClass().getName(), "Activity");
2666 }
2667 r.activity.mDecor = null;
2668 }
2669 WindowManagerImpl.getDefault().closeAll(token,
2670 r.activity.getClass().getName(), "Activity");
2671
2672 // Mocked out contexts won't be participating in the normal
2673 // process lifecycle, but if we're running with a proper
2674 // ApplicationContext we need to have it tear down things
2675 // cleanly.
2676 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002677 if (c instanceof ContextImpl) {
2678 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 r.activity.getClass().getName(), "Activity");
2680 }
2681 }
2682 if (finishing) {
2683 try {
2684 ActivityManagerNative.getDefault().activityDestroyed(token);
2685 } catch (RemoteException ex) {
2686 // If the system process has died, it's game over for everyone.
2687 }
2688 }
2689 }
2690
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002691 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 // If we are getting ready to gc after going to the background, well
2693 // we are back active so skip it.
2694 unscheduleGcIdler();
2695
2696 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002697
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002698 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002699 + tmp.token + " with configChanges=0x"
2700 + Integer.toHexString(configChanges));
2701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 // First: make sure we have the most recent configuration and most
2703 // recent version of the activity, or skip it if some previous call
2704 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002705 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 int N = mRelaunchingActivities.size();
2707 IBinder token = tmp.token;
2708 tmp = null;
2709 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002710 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 if (r.token == token) {
2712 tmp = r;
2713 mRelaunchingActivities.remove(i);
2714 i--;
2715 N--;
2716 }
2717 }
Bob Leee5408332009-09-04 18:31:17 -07002718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002720 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 return;
2722 }
Bob Leee5408332009-09-04 18:31:17 -07002723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 if (mPendingConfiguration != null) {
2725 changedConfig = mPendingConfiguration;
2726 mPendingConfiguration = null;
2727 }
2728 }
Bob Leee5408332009-09-04 18:31:17 -07002729
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002730 if (tmp.createdConfig != null) {
2731 // If the activity manager is passing us its current config,
2732 // assume that is really what we want regardless of what we
2733 // may have pending.
2734 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002735 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2736 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2737 if (changedConfig == null
2738 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2739 changedConfig = tmp.createdConfig;
2740 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002741 }
2742 }
2743
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002744 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002745 + tmp.token + ": changedConfig=" + changedConfig);
2746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 // If there was a pending configuration change, execute it first.
2748 if (changedConfig != null) {
2749 handleConfigurationChanged(changedConfig);
2750 }
Bob Leee5408332009-09-04 18:31:17 -07002751
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002752 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002753 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 if (r == null) {
2755 return;
2756 }
Bob Leee5408332009-09-04 18:31:17 -07002757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002759 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 Bundle savedState = null;
2762 if (!r.paused) {
2763 savedState = performPauseActivity(r.token, false, true);
2764 }
Bob Leee5408332009-09-04 18:31:17 -07002765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 r.activity = null;
2769 r.window = null;
2770 r.hideForNow = false;
2771 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002772 // Merge any pending results and pending intents; don't just replace them
2773 if (tmp.pendingResults != null) {
2774 if (r.pendingResults == null) {
2775 r.pendingResults = tmp.pendingResults;
2776 } else {
2777 r.pendingResults.addAll(tmp.pendingResults);
2778 }
2779 }
2780 if (tmp.pendingIntents != null) {
2781 if (r.pendingIntents == null) {
2782 r.pendingIntents = tmp.pendingIntents;
2783 } else {
2784 r.pendingIntents.addAll(tmp.pendingIntents);
2785 }
2786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 r.startsNotResumed = tmp.startsNotResumed;
2788 if (savedState != null) {
2789 r.state = savedState;
2790 }
Bob Leee5408332009-09-04 18:31:17 -07002791
Christopher Tateb70f3df2009-04-07 16:07:59 -07002792 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 }
2794
2795 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002796 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 Bitmap thumbnail = createThumbnailBitmap(r);
2798 CharSequence description = null;
2799 try {
2800 description = r.activity.onCreateDescription();
2801 } catch (Exception e) {
2802 if (!mInstrumentation.onException(r.activity, e)) {
2803 throw new RuntimeException(
2804 "Unable to create description of activity "
2805 + r.intent.getComponent().toShortString()
2806 + ": " + e.toString(), e);
2807 }
2808 }
2809 //System.out.println("Reporting top thumbnail " + thumbnail);
2810 try {
2811 ActivityManagerNative.getDefault().reportThumbnail(
2812 token, thumbnail, description);
2813 } catch (RemoteException ex) {
2814 }
2815 }
2816
2817 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2818 boolean allActivities, Configuration newConfig) {
2819 ArrayList<ComponentCallbacks> callbacks
2820 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002823 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002825 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 Activity a = ar.activity;
2827 if (a != null) {
2828 if (!ar.activity.mFinished && (allActivities ||
2829 (a != null && !ar.paused))) {
2830 // If the activity is currently resumed, its configuration
2831 // needs to change right now.
2832 callbacks.add(a);
2833 } else if (newConfig != null) {
2834 // Otherwise, we will tell it about the change
2835 // the next time it is resumed or shown. Note that
2836 // the activity manager may, before then, decide the
2837 // activity needs to be destroyed to handle its new
2838 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002839 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002840 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 ar.newConfig = newConfig;
2842 }
2843 }
2844 }
2845 }
2846 if (mServices.size() > 0) {
2847 Iterator<Service> it = mServices.values().iterator();
2848 while (it.hasNext()) {
2849 callbacks.add(it.next());
2850 }
2851 }
2852 synchronized (mProviderMap) {
2853 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002854 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 while (it.hasNext()) {
2856 callbacks.add(it.next().mLocalProvider);
2857 }
2858 }
2859 }
2860 final int N = mAllApplications.size();
2861 for (int i=0; i<N; i++) {
2862 callbacks.add(mAllApplications.get(i));
2863 }
Bob Leee5408332009-09-04 18:31:17 -07002864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 return callbacks;
2866 }
Bob Leee5408332009-09-04 18:31:17 -07002867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 private final void performConfigurationChanged(
2869 ComponentCallbacks cb, Configuration config) {
2870 // Only for Activity objects, check that they actually call up to their
2871 // superclass implementation. ComponentCallbacks is an interface, so
2872 // we check the runtime type and act accordingly.
2873 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2874 if (activity != null) {
2875 activity.mCalled = false;
2876 }
Bob Leee5408332009-09-04 18:31:17 -07002877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 boolean shouldChangeConfig = false;
2879 if ((activity == null) || (activity.mCurrentConfig == null)) {
2880 shouldChangeConfig = true;
2881 } else {
Bob Leee5408332009-09-04 18:31:17 -07002882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 // If the new config is the same as the config this Activity
2884 // is already running with then don't bother calling
2885 // onConfigurationChanged
2886 int diff = activity.mCurrentConfig.diff(config);
2887 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 // If this activity doesn't handle any of the config changes
2890 // then don't bother calling onConfigurationChanged as we're
2891 // going to destroy it.
2892 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2893 shouldChangeConfig = true;
2894 }
2895 }
2896 }
Bob Leee5408332009-09-04 18:31:17 -07002897
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002898 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002899 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 if (shouldChangeConfig) {
2901 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 if (activity != null) {
2904 if (!activity.mCalled) {
2905 throw new SuperNotCalledException(
2906 "Activity " + activity.getLocalClassName() +
2907 " did not call through to super.onConfigurationChanged()");
2908 }
2909 activity.mConfigChangeFlags = 0;
2910 activity.mCurrentConfig = new Configuration(config);
2911 }
2912 }
2913 }
2914
Dianne Hackbornae078162010-03-18 11:29:37 -07002915 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002916 if (mResConfiguration == null) {
2917 mResConfiguration = new Configuration();
2918 }
2919 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002920 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002921 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002922 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002923 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002924 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002925 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002926
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002927 // set it for java, this also affects newly created Resources
2928 if (config.locale != null) {
2929 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 }
Bob Leee5408332009-09-04 18:31:17 -07002931
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002932 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07002933
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002934 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002935 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002936
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002937 Iterator<WeakReference<Resources>> it =
2938 mActiveResources.values().iterator();
2939 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
2940 // mActiveResources.entrySet().iterator();
2941 while (it.hasNext()) {
2942 WeakReference<Resources> v = it.next();
2943 Resources r = v.get();
2944 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002945 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002946 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002947 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002948 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002949 // + " " + r + ": " + r.getConfiguration());
2950 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002951 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002952 it.remove();
2953 }
2954 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002955
2956 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002957 }
2958
2959 final void handleConfigurationChanged(Configuration config) {
2960
2961 ArrayList<ComponentCallbacks> callbacks = null;
2962
2963 synchronized (mPackages) {
2964 if (mPendingConfiguration != null) {
2965 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
2966 config = mPendingConfiguration;
2967 }
2968 mPendingConfiguration = null;
2969 }
2970
2971 if (config == null) {
2972 return;
2973 }
2974
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002975 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002976 + config);
2977
2978 applyConfigurationToResourcesLocked(config);
2979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 if (mConfiguration == null) {
2981 mConfiguration = new Configuration();
2982 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002983 if (!mConfiguration.isOtherSeqNewer(config)) {
2984 return;
2985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07002987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 callbacks = collectComponentCallbacksLocked(false, config);
2989 }
Bob Leee5408332009-09-04 18:31:17 -07002990
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002991 if (callbacks != null) {
2992 final int N = callbacks.size();
2993 for (int i=0; i<N; i++) {
2994 performConfigurationChanged(callbacks.get(i), config);
2995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 }
2997 }
2998
2999 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003000 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 if (r == null || r.activity == null) {
3002 return;
3003 }
Bob Leee5408332009-09-04 18:31:17 -07003004
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003005 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003006 + r.activityInfo.name);
3007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 performConfigurationChanged(r.activity, mConfiguration);
3009 }
3010
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003011 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003012 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003013 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003014 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3015 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003016 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003017 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003018 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003019 } finally {
3020 try {
3021 pcd.fd.close();
3022 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003023 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003024 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003025 }
3026 } else {
3027 Debug.stopMethodTracing();
3028 }
3029 }
Bob Leee5408332009-09-04 18:31:17 -07003030
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003031 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3032 boolean hasPkgInfo = false;
3033 if (packages != null) {
3034 for (int i=packages.length-1; i>=0; i--) {
3035 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3036 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003037 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003038 ref = mPackages.get(packages[i]);
3039 if (ref != null && ref.get() != null) {
3040 hasPkgInfo = true;
3041 } else {
3042 ref = mResourcePackages.get(packages[i]);
3043 if (ref != null && ref.get() != null) {
3044 hasPkgInfo = true;
3045 }
3046 }
3047 }
3048 mPackages.remove(packages[i]);
3049 mResourcePackages.remove(packages[i]);
3050 }
3051 }
3052 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3053 hasPkgInfo);
3054 }
3055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 final void handleLowMemory() {
3057 ArrayList<ComponentCallbacks> callbacks
3058 = new ArrayList<ComponentCallbacks>();
3059
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003060 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 callbacks = collectComponentCallbacksLocked(true, null);
3062 }
Bob Leee5408332009-09-04 18:31:17 -07003063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 final int N = callbacks.size();
3065 for (int i=0; i<N; i++) {
3066 callbacks.get(i).onLowMemory();
3067 }
3068
Chris Tatece229052009-03-25 16:44:52 -07003069 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3070 if (Process.myUid() != Process.SYSTEM_UID) {
3071 int sqliteReleased = SQLiteDatabase.releaseMemory();
3072 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3073 }
Bob Leee5408332009-09-04 18:31:17 -07003074
Mike Reedcaf0df12009-04-27 14:32:05 -04003075 // Ask graphics to free up as much as possible (font/image caches)
3076 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077
3078 BinderInternal.forceGc("mem");
3079 }
3080
3081 private final void handleBindApplication(AppBindData data) {
3082 mBoundApplication = data;
3083 mConfiguration = new Configuration(data.config);
3084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003086 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 android.ddm.DdmHandleAppName.setAppName(data.processName);
3088
3089 /*
3090 * Before spawning a new process, reset the time zone to be the system time zone.
3091 * This needs to be done because the system time zone could have changed after the
3092 * the spawning of this process. Without doing this this process would have the incorrect
3093 * system time zone.
3094 */
3095 TimeZone.setDefault(null);
3096
3097 /*
3098 * Initialize the default locale in this process for the reasons we set the time zone.
3099 */
3100 Locale.setDefault(data.config.locale);
3101
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003102 /*
3103 * Update the system configuration since its preloaded and might not
3104 * reflect configuration changes. The configuration object passed
3105 * in AppBindData can be safely assumed to be up to date
3106 */
3107 Resources.getSystem().updateConfiguration(mConfiguration, null);
3108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 data.info = getPackageInfoNoCheck(data.appInfo);
3110
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003111 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003112 * For system applications on userdebug/eng builds, log stack
3113 * traces of disk and network access to dropbox for analysis.
3114 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003115 if ((data.appInfo.flags &
3116 (ApplicationInfo.FLAG_SYSTEM |
3117 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0 &&
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003118 !"user".equals(Build.TYPE)) {
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07003119 StrictMode.setThreadPolicy(
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003120 StrictMode.DISALLOW_DISK_WRITE |
3121 StrictMode.DISALLOW_DISK_READ |
3122 StrictMode.DISALLOW_NETWORK |
3123 StrictMode.PENALTY_DROPBOX);
3124 }
3125
3126 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003127 * Switch this process to density compatibility mode if needed.
3128 */
3129 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3130 == 0) {
3131 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3132 }
Bob Leee5408332009-09-04 18:31:17 -07003133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3135 // XXX should have option to change the port.
3136 Debug.changeDebugPort(8100);
3137 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003138 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 + " is waiting for the debugger on port 8100...");
3140
3141 IActivityManager mgr = ActivityManagerNative.getDefault();
3142 try {
3143 mgr.showWaitingForDebugger(mAppThread, true);
3144 } catch (RemoteException ex) {
3145 }
3146
3147 Debug.waitForDebugger();
3148
3149 try {
3150 mgr.showWaitingForDebugger(mAppThread, false);
3151 } catch (RemoteException ex) {
3152 }
3153
3154 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003155 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 + " can be debugged on port 8100...");
3157 }
3158 }
3159
3160 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003161 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 appContext.init(data.info, null, this);
3163 InstrumentationInfo ii = null;
3164 try {
3165 ii = appContext.getPackageManager().
3166 getInstrumentationInfo(data.instrumentationName, 0);
3167 } catch (PackageManager.NameNotFoundException e) {
3168 }
3169 if (ii == null) {
3170 throw new RuntimeException(
3171 "Unable to find instrumentation info for: "
3172 + data.instrumentationName);
3173 }
3174
3175 mInstrumentationAppDir = ii.sourceDir;
3176 mInstrumentationAppPackage = ii.packageName;
3177 mInstrumentedAppDir = data.info.getAppDir();
3178
3179 ApplicationInfo instrApp = new ApplicationInfo();
3180 instrApp.packageName = ii.packageName;
3181 instrApp.sourceDir = ii.sourceDir;
3182 instrApp.publicSourceDir = ii.publicSourceDir;
3183 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003184 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003185 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003187 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 instrContext.init(pi, null, this);
3189
3190 try {
3191 java.lang.ClassLoader cl = instrContext.getClassLoader();
3192 mInstrumentation = (Instrumentation)
3193 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3194 } catch (Exception e) {
3195 throw new RuntimeException(
3196 "Unable to instantiate instrumentation "
3197 + data.instrumentationName + ": " + e.toString(), e);
3198 }
3199
3200 mInstrumentation.init(this, instrContext, appContext,
3201 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3202
3203 if (data.profileFile != null && !ii.handleProfiling) {
3204 data.handlingProfiling = true;
3205 File file = new File(data.profileFile);
3206 file.getParentFile().mkdirs();
3207 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3208 }
3209
3210 try {
3211 mInstrumentation.onCreate(data.instrumentationArgs);
3212 }
3213 catch (Exception e) {
3214 throw new RuntimeException(
3215 "Exception thrown in onCreate() of "
3216 + data.instrumentationName + ": " + e.toString(), e);
3217 }
3218
3219 } else {
3220 mInstrumentation = new Instrumentation();
3221 }
3222
Christopher Tate181fafa2009-05-14 11:12:14 -07003223 // If the app is being launched for full backup or restore, bring it up in
3224 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003225 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 mInitialApplication = app;
3227
3228 List<ProviderInfo> providers = data.providers;
3229 if (providers != null) {
3230 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003231 // For process that contain content providers, we want to
3232 // ensure that the JIT is enabled "at some point".
3233 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 }
3235
3236 try {
3237 mInstrumentation.callApplicationOnCreate(app);
3238 } catch (Exception e) {
3239 if (!mInstrumentation.onException(app, e)) {
3240 throw new RuntimeException(
3241 "Unable to create application " + app.getClass().getName()
3242 + ": " + e.toString(), e);
3243 }
3244 }
3245 }
3246
3247 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3248 IActivityManager am = ActivityManagerNative.getDefault();
3249 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3250 Debug.stopMethodTracing();
3251 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003252 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 // + ", app thr: " + mAppThread);
3254 try {
3255 am.finishInstrumentation(mAppThread, resultCode, results);
3256 } catch (RemoteException ex) {
3257 }
3258 }
3259
3260 private final void installContentProviders(
3261 Context context, List<ProviderInfo> providers) {
3262 final ArrayList<IActivityManager.ContentProviderHolder> results =
3263 new ArrayList<IActivityManager.ContentProviderHolder>();
3264
3265 Iterator<ProviderInfo> i = providers.iterator();
3266 while (i.hasNext()) {
3267 ProviderInfo cpi = i.next();
3268 StringBuilder buf = new StringBuilder(128);
3269 buf.append("Publishing provider ");
3270 buf.append(cpi.authority);
3271 buf.append(": ");
3272 buf.append(cpi.name);
3273 Log.i(TAG, buf.toString());
3274 IContentProvider cp = installProvider(context, null, cpi, false);
3275 if (cp != null) {
3276 IActivityManager.ContentProviderHolder cph =
3277 new IActivityManager.ContentProviderHolder(cpi);
3278 cph.provider = cp;
3279 results.add(cph);
3280 // Don't ever unload this provider from the process.
3281 synchronized(mProviderMap) {
3282 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3283 }
3284 }
3285 }
3286
3287 try {
3288 ActivityManagerNative.getDefault().publishContentProviders(
3289 getApplicationThread(), results);
3290 } catch (RemoteException ex) {
3291 }
3292 }
3293
3294 private final IContentProvider getProvider(Context context, String name) {
3295 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003296 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 if (pr != null) {
3298 return pr.mProvider;
3299 }
3300 }
3301
3302 IActivityManager.ContentProviderHolder holder = null;
3303 try {
3304 holder = ActivityManagerNative.getDefault().getContentProvider(
3305 getApplicationThread(), name);
3306 } catch (RemoteException ex) {
3307 }
3308 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003309 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 return null;
3311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312
3313 IContentProvider prov = installProvider(context, holder.provider,
3314 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003315 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 if (holder.noReleaseNeeded || holder.provider == null) {
3317 // We are not going to release the provider if it is an external
3318 // provider that doesn't care about being released, or if it is
3319 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003320 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 synchronized(mProviderMap) {
3322 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3323 }
3324 }
3325 return prov;
3326 }
3327
3328 public final IContentProvider acquireProvider(Context c, String name) {
3329 IContentProvider provider = getProvider(c, name);
3330 if(provider == null)
3331 return null;
3332 IBinder jBinder = provider.asBinder();
3333 synchronized(mProviderMap) {
3334 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3335 if(prc == null) {
3336 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3337 } else {
3338 prc.count++;
3339 } //end else
3340 } //end synchronized
3341 return provider;
3342 }
3343
3344 public final boolean releaseProvider(IContentProvider provider) {
3345 if(provider == null) {
3346 return false;
3347 }
3348 IBinder jBinder = provider.asBinder();
3349 synchronized(mProviderMap) {
3350 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3351 if(prc == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003352 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldnt be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 return false;
3354 } else {
3355 prc.count--;
3356 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003357 // Schedule the actual remove asynchronously, since we
3358 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003359 // TODO: it would be nice to post a delayed message, so
3360 // if we come back and need the same provider quickly
3361 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003362 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3363 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 } //end if
3365 } //end else
3366 } //end synchronized
3367 return true;
3368 }
3369
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003370 final void completeRemoveProvider(IContentProvider provider) {
3371 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003372 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003373 synchronized(mProviderMap) {
3374 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3375 if(prc != null && prc.count == 0) {
3376 mProviderRefCountMap.remove(jBinder);
3377 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003378 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003379 }
3380 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003381
3382 if (name != null) {
3383 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003384 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003385 "ActivityManagerNative.removeContentProvider(" + name);
3386 ActivityManagerNative.getDefault().removeContentProvider(
3387 getApplicationThread(), name);
3388 } catch (RemoteException e) {
3389 //do nothing content provider object is dead any way
3390 } //end catch
3391 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003392 }
3393
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003394 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003396 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 }
3398 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003400 String name = null;
3401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003403 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003405 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 IBinder myBinder = pr.mProvider.asBinder();
3407 if (myBinder == providerBinder) {
3408 //find if its published by this process itself
3409 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003410 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003411 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003413 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 "death recipient");
3415 //content provider is in another process
3416 myBinder.unlinkToDeath(pr, 0);
3417 iter.remove();
3418 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003419 if(name == null) {
3420 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 }
3422 } //end if myBinder
3423 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003424
3425 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 }
3427
3428 final void removeDeadProvider(String name, IContentProvider provider) {
3429 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003430 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003432 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003433 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003434 if (removed != null) {
3435 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 }
3438 }
3439 }
3440
3441 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003442 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003444 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003445 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003446 if (removed != null) {
3447 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 }
3450 }
3451
3452 private final IContentProvider installProvider(Context context,
3453 IContentProvider provider, ProviderInfo info, boolean noisy) {
3454 ContentProvider localProvider = null;
3455 if (provider == null) {
3456 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003457 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 + info.name);
3459 }
3460 Context c = null;
3461 ApplicationInfo ai = info.applicationInfo;
3462 if (context.getPackageName().equals(ai.packageName)) {
3463 c = context;
3464 } else if (mInitialApplication != null &&
3465 mInitialApplication.getPackageName().equals(ai.packageName)) {
3466 c = mInitialApplication;
3467 } else {
3468 try {
3469 c = context.createPackageContext(ai.packageName,
3470 Context.CONTEXT_INCLUDE_CODE);
3471 } catch (PackageManager.NameNotFoundException e) {
3472 }
3473 }
3474 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003475 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 ai.packageName +
3477 " while loading content provider " +
3478 info.name);
3479 return null;
3480 }
3481 try {
3482 final java.lang.ClassLoader cl = c.getClassLoader();
3483 localProvider = (ContentProvider)cl.
3484 loadClass(info.name).newInstance();
3485 provider = localProvider.getIContentProvider();
3486 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003487 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 info.name + " from sourceDir " +
3489 info.applicationInfo.sourceDir);
3490 return null;
3491 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003492 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 TAG, "Instantiating local provider " + info.name);
3494 // XXX Need to create the correct context for this provider.
3495 localProvider.attachInfo(c, info);
3496 } catch (java.lang.Exception e) {
3497 if (!mInstrumentation.onException(null, e)) {
3498 throw new RuntimeException(
3499 "Unable to get provider " + info.name
3500 + ": " + e.toString(), e);
3501 }
3502 return null;
3503 }
3504 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003505 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 + info.name);
3507 }
3508
3509 synchronized (mProviderMap) {
3510 // Cache the pointer for the remote provider.
3511 String names[] = PATTERN_SEMICOLON.split(info.authority);
3512 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003513 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 localProvider);
3515 try {
3516 provider.asBinder().linkToDeath(pr, 0);
3517 mProviderMap.put(names[i], pr);
3518 } catch (RemoteException e) {
3519 return null;
3520 }
3521 }
3522 if (localProvider != null) {
3523 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003524 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 }
3526 }
3527
3528 return provider;
3529 }
3530
3531 private final void attach(boolean system) {
3532 sThreadLocal.set(this);
3533 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003535 ViewRoot.addFirstDrawHandler(new Runnable() {
3536 public void run() {
3537 ensureJitEnabled();
3538 }
3539 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3541 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3542 IActivityManager mgr = ActivityManagerNative.getDefault();
3543 try {
3544 mgr.attachApplication(mAppThread);
3545 } catch (RemoteException ex) {
3546 }
3547 } else {
3548 // Don't set application object here -- if the system crashes,
3549 // we can't display an alert, we just want to die die die.
3550 android.ddm.DdmHandleAppName.setAppName("system_process");
3551 try {
3552 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003553 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 context.init(getSystemContext().mPackageInfo, null, this);
3555 Application app = Instrumentation.newApplication(Application.class, context);
3556 mAllApplications.add(app);
3557 mInitialApplication = app;
3558 app.onCreate();
3559 } catch (Exception e) {
3560 throw new RuntimeException(
3561 "Unable to instantiate Application():" + e.toString(), e);
3562 }
3563 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003564
3565 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3566 public void onConfigurationChanged(Configuration newConfig) {
3567 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003568 // We need to apply this change to the resources
3569 // immediately, because upon returning the view
3570 // hierarchy will be informed about it.
3571 if (applyConfigurationToResourcesLocked(newConfig)) {
3572 // This actually changed the resources! Tell
3573 // everyone about it.
3574 if (mPendingConfiguration == null ||
3575 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3576 mPendingConfiguration = newConfig;
3577
3578 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3579 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003580 }
3581 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003582 }
3583 public void onLowMemory() {
3584 }
3585 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 }
3587
3588 private final void detach()
3589 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 sThreadLocal.set(null);
3591 }
3592
3593 public static final ActivityThread systemMain() {
3594 ActivityThread thread = new ActivityThread();
3595 thread.attach(true);
3596 return thread;
3597 }
3598
3599 public final void installSystemProviders(List providers) {
3600 if (providers != null) {
3601 installContentProviders(mInitialApplication,
3602 (List<ProviderInfo>)providers);
3603 }
3604 }
3605
3606 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003607 SamplingProfilerIntegration.start();
3608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 Process.setArgV0("<pre-initialized>");
3610
3611 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003612 if (sMainThreadHandler == null) {
3613 sMainThreadHandler = new Handler();
3614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615
3616 ActivityThread thread = new ActivityThread();
3617 thread.attach(false);
3618
3619 Looper.loop();
3620
3621 if (Process.supportsProcesses()) {
3622 throw new RuntimeException("Main thread loop unexpectedly exited");
3623 }
3624
3625 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003626 String name = (thread.mInitialApplication != null)
3627 ? thread.mInitialApplication.getPackageName()
3628 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003629 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 }
3631}