blob: d8b525346362cf007ff68029002a47cbb57b2ea4 [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 {
840 public static final int LAUNCH_ACTIVITY = 100;
841 public static final int PAUSE_ACTIVITY = 101;
842 public static final int PAUSE_ACTIVITY_FINISHING= 102;
843 public static final int STOP_ACTIVITY_SHOW = 103;
844 public static final int STOP_ACTIVITY_HIDE = 104;
845 public static final int SHOW_WINDOW = 105;
846 public static final int HIDE_WINDOW = 106;
847 public static final int RESUME_ACTIVITY = 107;
848 public static final int SEND_RESULT = 108;
849 public static final int DESTROY_ACTIVITY = 109;
850 public static final int BIND_APPLICATION = 110;
851 public static final int EXIT_APPLICATION = 111;
852 public static final int NEW_INTENT = 112;
853 public static final int RECEIVER = 113;
854 public static final int CREATE_SERVICE = 114;
855 public static final int SERVICE_ARGS = 115;
856 public static final int STOP_SERVICE = 116;
857 public static final int REQUEST_THUMBNAIL = 117;
858 public static final int CONFIGURATION_CHANGED = 118;
859 public static final int CLEAN_UP_CONTEXT = 119;
860 public static final int GC_WHEN_IDLE = 120;
861 public static final int BIND_SERVICE = 121;
862 public static final int UNBIND_SERVICE = 122;
863 public static final int DUMP_SERVICE = 123;
864 public static final int LOW_MEMORY = 124;
865 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
866 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800867 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700868 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700869 public static final int DESTROY_BACKUP_AGENT = 129;
870 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700871 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800872 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700873 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700874 public static final int SCHEDULE_CRASH = 134;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 String codeToString(int code) {
876 if (localLOGV) {
877 switch (code) {
878 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
879 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
880 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
881 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
882 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
883 case SHOW_WINDOW: return "SHOW_WINDOW";
884 case HIDE_WINDOW: return "HIDE_WINDOW";
885 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
886 case SEND_RESULT: return "SEND_RESULT";
887 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
888 case BIND_APPLICATION: return "BIND_APPLICATION";
889 case EXIT_APPLICATION: return "EXIT_APPLICATION";
890 case NEW_INTENT: return "NEW_INTENT";
891 case RECEIVER: return "RECEIVER";
892 case CREATE_SERVICE: return "CREATE_SERVICE";
893 case SERVICE_ARGS: return "SERVICE_ARGS";
894 case STOP_SERVICE: return "STOP_SERVICE";
895 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
896 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
897 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
898 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
899 case BIND_SERVICE: return "BIND_SERVICE";
900 case UNBIND_SERVICE: return "UNBIND_SERVICE";
901 case DUMP_SERVICE: return "DUMP_SERVICE";
902 case LOW_MEMORY: return "LOW_MEMORY";
903 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
904 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800905 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700906 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
907 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700908 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700909 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800910 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700911 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700912 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 }
914 }
915 return "(unknown)";
916 }
917 public void handleMessage(Message msg) {
918 switch (msg.what) {
919 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700920 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921
922 r.packageInfo = getPackageInfoNoCheck(
923 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700924 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 } break;
926 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700927 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 handleRelaunchActivity(r, msg.arg1);
929 } break;
930 case PAUSE_ACTIVITY:
931 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700932 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 break;
934 case PAUSE_ACTIVITY_FINISHING:
935 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
936 break;
937 case STOP_ACTIVITY_SHOW:
938 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
939 break;
940 case STOP_ACTIVITY_HIDE:
941 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
942 break;
943 case SHOW_WINDOW:
944 handleWindowVisibility((IBinder)msg.obj, true);
945 break;
946 case HIDE_WINDOW:
947 handleWindowVisibility((IBinder)msg.obj, false);
948 break;
949 case RESUME_ACTIVITY:
950 handleResumeActivity((IBinder)msg.obj, true,
951 msg.arg1 != 0);
952 break;
953 case SEND_RESULT:
954 handleSendResult((ResultData)msg.obj);
955 break;
956 case DESTROY_ACTIVITY:
957 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
958 msg.arg2, false);
959 break;
960 case BIND_APPLICATION:
961 AppBindData data = (AppBindData)msg.obj;
962 handleBindApplication(data);
963 break;
964 case EXIT_APPLICATION:
965 if (mInitialApplication != null) {
966 mInitialApplication.onTerminate();
967 }
968 Looper.myLooper().quit();
969 break;
970 case NEW_INTENT:
971 handleNewIntent((NewIntentData)msg.obj);
972 break;
973 case RECEIVER:
974 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700975 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 break;
977 case CREATE_SERVICE:
978 handleCreateService((CreateServiceData)msg.obj);
979 break;
980 case BIND_SERVICE:
981 handleBindService((BindServiceData)msg.obj);
982 break;
983 case UNBIND_SERVICE:
984 handleUnbindService((BindServiceData)msg.obj);
985 break;
986 case SERVICE_ARGS:
987 handleServiceArgs((ServiceArgsData)msg.obj);
988 break;
989 case STOP_SERVICE:
990 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700991 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 break;
993 case REQUEST_THUMBNAIL:
994 handleRequestThumbnail((IBinder)msg.obj);
995 break;
996 case CONFIGURATION_CHANGED:
997 handleConfigurationChanged((Configuration)msg.obj);
998 break;
999 case CLEAN_UP_CONTEXT:
1000 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1001 cci.context.performFinalCleanup(cci.who, cci.what);
1002 break;
1003 case GC_WHEN_IDLE:
1004 scheduleGcIdler();
1005 break;
1006 case DUMP_SERVICE:
1007 handleDumpService((DumpServiceInfo)msg.obj);
1008 break;
1009 case LOW_MEMORY:
1010 handleLowMemory();
1011 break;
1012 case ACTIVITY_CONFIGURATION_CHANGED:
1013 handleActivityConfigurationChanged((IBinder)msg.obj);
1014 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001015 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001016 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001017 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001018 case CREATE_BACKUP_AGENT:
1019 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1020 break;
1021 case DESTROY_BACKUP_AGENT:
1022 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1023 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001024 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001025 Process.killProcess(Process.myPid());
1026 break;
1027 case REMOVE_PROVIDER:
1028 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001029 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001030 case ENABLE_JIT:
1031 ensureJitEnabled();
1032 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001033 case DISPATCH_PACKAGE_BROADCAST:
1034 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1035 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001036 case SCHEDULE_CRASH:
1037 throw new RemoteServiceException((String)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039 }
Bob Leee5408332009-09-04 18:31:17 -07001040
1041 void maybeSnapshot() {
1042 if (mBoundApplication != null) {
1043 SamplingProfilerIntegration.writeSnapshot(
1044 mBoundApplication.processName);
1045 }
1046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048
1049 private final class Idler implements MessageQueue.IdleHandler {
1050 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001051 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 if (a != null) {
1053 mNewActivities = null;
1054 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001055 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001057 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 TAG, "Reporting idle of " + a +
1059 " finished=" +
1060 (a.activity != null ? a.activity.mFinished : false));
1061 if (a.activity != null && !a.activity.mFinished) {
1062 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001063 am.activityIdle(a.token, a.createdConfig);
1064 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 } catch (RemoteException ex) {
1066 }
1067 }
1068 prev = a;
1069 a = a.nextIdle;
1070 prev.nextIdle = null;
1071 } while (a != null);
1072 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001073 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 return false;
1075 }
1076 }
1077
1078 final class GcIdler implements MessageQueue.IdleHandler {
1079 public final boolean queueIdle() {
1080 doGcIfNeeded();
1081 return false;
1082 }
1083 }
1084
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001085 private final static class ResourcesKey {
1086 final private String mResDir;
1087 final private float mScale;
1088 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001089
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001090 ResourcesKey(String resDir, float scale) {
1091 mResDir = resDir;
1092 mScale = scale;
1093 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1094 }
Bob Leee5408332009-09-04 18:31:17 -07001095
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001096 @Override
1097 public int hashCode() {
1098 return mHash;
1099 }
1100
1101 @Override
1102 public boolean equals(Object obj) {
1103 if (!(obj instanceof ResourcesKey)) {
1104 return false;
1105 }
1106 ResourcesKey peer = (ResourcesKey) obj;
1107 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1108 }
1109 }
1110
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001111 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001112 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001115 public static final String currentPackageName() {
1116 ActivityThread am = currentActivityThread();
1117 return (am != null && am.mBoundApplication != null)
1118 ? am.mBoundApplication.processName : null;
1119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001121 public static final Application currentApplication() {
1122 ActivityThread am = currentActivityThread();
1123 return am != null ? am.mInitialApplication : null;
1124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001126 public static IPackageManager getPackageManager() {
1127 if (sPackageManager != null) {
1128 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1129 return sPackageManager;
1130 }
1131 IBinder b = ServiceManager.getService("package");
1132 //Slog.v("PackageManager", "default service binder = " + b);
1133 sPackageManager = IPackageManager.Stub.asInterface(b);
1134 //Slog.v("PackageManager", "default service = " + sPackageManager);
1135 return sPackageManager;
1136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001138 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1139 if (mDisplayMetrics != null && !forceUpdate) {
1140 return mDisplayMetrics;
1141 }
1142 if (mDisplay == null) {
1143 WindowManager wm = WindowManagerImpl.getDefault();
1144 mDisplay = wm.getDefaultDisplay();
1145 }
1146 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1147 mDisplay.getMetrics(metrics);
1148 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1149 // + metrics.heightPixels + " den=" + metrics.density
1150 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1151 return metrics;
1152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001154 /**
1155 * Creates the top level Resources for applications with the given compatibility info.
1156 *
1157 * @param resDir the resource directory.
1158 * @param compInfo the compability info. It will use the default compatibility info when it's
1159 * null.
1160 */
1161 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1162 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1163 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001165 // Resources is app scale dependent.
1166 if (false) {
1167 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1168 + compInfo.applicationScale);
1169 }
1170 WeakReference<Resources> wr = mActiveResources.get(key);
1171 r = wr != null ? wr.get() : null;
1172 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1173 if (r != null && r.getAssets().isUpToDate()) {
1174 if (false) {
1175 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1176 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1177 }
1178 return r;
1179 }
1180 }
1181
1182 //if (r != null) {
1183 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1184 // + r + " " + resDir);
1185 //}
1186
1187 AssetManager assets = new AssetManager();
1188 if (assets.addAssetPath(resDir) == 0) {
1189 return null;
1190 }
1191
1192 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1193 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1194 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1195 if (false) {
1196 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1197 + r.getConfiguration() + " appScale="
1198 + r.getCompatibilityInfo().applicationScale);
1199 }
1200
1201 synchronized (mPackages) {
1202 WeakReference<Resources> wr = mActiveResources.get(key);
1203 Resources existing = wr != null ? wr.get() : null;
1204 if (existing != null && existing.getAssets().isUpToDate()) {
1205 // Someone else already created the resources while we were
1206 // unlocked; go ahead and use theirs.
1207 r.getAssets().close();
1208 return existing;
1209 }
1210
1211 // XXX need to remove entries when weak references go away
1212 mActiveResources.put(key, new WeakReference<Resources>(r));
1213 return r;
1214 }
1215 }
1216
1217 /**
1218 * Creates the top level resources for the given package.
1219 */
1220 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1221 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1222 }
1223
1224 final Handler getHandler() {
1225 return mH;
1226 }
1227
1228 public final LoadedApk getPackageInfo(String packageName, int flags) {
1229 synchronized (mPackages) {
1230 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1232 ref = mPackages.get(packageName);
1233 } else {
1234 ref = mResourcePackages.get(packageName);
1235 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001236 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001237 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001238 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1239 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 if (packageInfo != null && (packageInfo.mResources == null
1241 || packageInfo.mResources.getAssets().isUpToDate())) {
1242 if (packageInfo.isSecurityViolation()
1243 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1244 throw new SecurityException(
1245 "Requesting code from " + packageName
1246 + " to be run in process "
1247 + mBoundApplication.processName
1248 + "/" + mBoundApplication.appInfo.uid);
1249 }
1250 return packageInfo;
1251 }
1252 }
1253
1254 ApplicationInfo ai = null;
1255 try {
1256 ai = getPackageManager().getApplicationInfo(packageName,
1257 PackageManager.GET_SHARED_LIBRARY_FILES);
1258 } catch (RemoteException e) {
1259 }
1260
1261 if (ai != null) {
1262 return getPackageInfo(ai, flags);
1263 }
1264
1265 return null;
1266 }
1267
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001268 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1270 boolean securityViolation = includeCode && ai.uid != 0
1271 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1272 ? ai.uid != mBoundApplication.appInfo.uid : true);
1273 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1274 |Context.CONTEXT_IGNORE_SECURITY))
1275 == Context.CONTEXT_INCLUDE_CODE) {
1276 if (securityViolation) {
1277 String msg = "Requesting code from " + ai.packageName
1278 + " (with uid " + ai.uid + ")";
1279 if (mBoundApplication != null) {
1280 msg = msg + " to be run in process "
1281 + mBoundApplication.processName + " (with uid "
1282 + mBoundApplication.appInfo.uid + ")";
1283 }
1284 throw new SecurityException(msg);
1285 }
1286 }
1287 return getPackageInfo(ai, null, securityViolation, includeCode);
1288 }
1289
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001290 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 return getPackageInfo(ai, null, false, true);
1292 }
1293
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001294 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1296 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001297 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 if (includeCode) {
1299 ref = mPackages.get(aInfo.packageName);
1300 } else {
1301 ref = mResourcePackages.get(aInfo.packageName);
1302 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001303 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 if (packageInfo == null || (packageInfo.mResources != null
1305 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001306 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 : "Loading resource-only package ") + aInfo.packageName
1308 + " (in " + (mBoundApplication != null
1309 ? mBoundApplication.processName : null)
1310 + ")");
1311 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001312 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 securityViolation, includeCode &&
1314 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1315 if (includeCode) {
1316 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001317 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 } else {
1319 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001320 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
1322 }
1323 return packageInfo;
1324 }
1325 }
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 ActivityThread() {
1328 }
1329
1330 public ApplicationThread getApplicationThread()
1331 {
1332 return mAppThread;
1333 }
1334
1335 public Instrumentation getInstrumentation()
1336 {
1337 return mInstrumentation;
1338 }
1339
1340 public Configuration getConfiguration() {
1341 return mConfiguration;
1342 }
1343
1344 public boolean isProfiling() {
1345 return mBoundApplication != null && mBoundApplication.profileFile != null;
1346 }
1347
1348 public String getProfileFilePath() {
1349 return mBoundApplication.profileFile;
1350 }
1351
1352 public Looper getLooper() {
1353 return mLooper;
1354 }
1355
1356 public Application getApplication() {
1357 return mInitialApplication;
1358 }
Bob Leee5408332009-09-04 18:31:17 -07001359
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001360 public String getProcessName() {
1361 return mBoundApplication.processName;
1362 }
Bob Leee5408332009-09-04 18:31:17 -07001363
Dianne Hackborn21556372010-02-04 16:34:40 -08001364 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 synchronized (this) {
1366 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001367 ContextImpl context =
1368 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001369 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 context.init(info, null, this);
1371 context.getResources().updateConfiguration(
1372 getConfiguration(), getDisplayMetricsLocked(false));
1373 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001374 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 // + ": " + context.getResources().getConfiguration());
1376 }
1377 }
1378 return mSystemContext;
1379 }
1380
Mike Cleron432b7132009-09-24 15:28:29 -07001381 public void installSystemApplicationInfo(ApplicationInfo info) {
1382 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001383 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001384 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001385 }
1386 }
1387
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001388 void ensureJitEnabled() {
1389 if (!mJitEnabled) {
1390 mJitEnabled = true;
1391 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1392 }
1393 }
1394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 void scheduleGcIdler() {
1396 if (!mGcIdlerScheduled) {
1397 mGcIdlerScheduled = true;
1398 Looper.myQueue().addIdleHandler(mGcIdler);
1399 }
1400 mH.removeMessages(H.GC_WHEN_IDLE);
1401 }
1402
1403 void unscheduleGcIdler() {
1404 if (mGcIdlerScheduled) {
1405 mGcIdlerScheduled = false;
1406 Looper.myQueue().removeIdleHandler(mGcIdler);
1407 }
1408 mH.removeMessages(H.GC_WHEN_IDLE);
1409 }
1410
1411 void doGcIfNeeded() {
1412 mGcIdlerScheduled = false;
1413 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001414 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 // + "m now=" + now);
1416 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001417 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 BinderInternal.forceGc("bg");
1419 }
1420 }
1421
1422 public final ActivityInfo resolveActivityInfo(Intent intent) {
1423 ActivityInfo aInfo = intent.resolveActivityInfo(
1424 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1425 if (aInfo == null) {
1426 // Throw an exception.
1427 Instrumentation.checkStartActivityResult(
1428 IActivityManager.START_CLASS_NOT_FOUND, intent);
1429 }
1430 return aInfo;
1431 }
Bob Leee5408332009-09-04 18:31:17 -07001432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
1435 Object lastNonConfigurationInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001436 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001438 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 r.intent = intent;
1440 r.state = state;
1441 r.parent = parent;
1442 r.embeddedID = id;
1443 r.activityInfo = activityInfo;
1444 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
1445 if (localLOGV) {
1446 ComponentName compname = intent.getComponent();
1447 String name;
1448 if (compname != null) {
1449 name = compname.toShortString();
1450 } else {
1451 name = "(Intent " + intent + ").getComponent() returned null";
1452 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001453 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 + ", comp=" + name
1455 + ", token=" + token);
1456 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001457 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
1459
1460 public final Activity getActivity(IBinder token) {
1461 return mActivities.get(token).activity;
1462 }
1463
1464 public final void sendActivityResult(
1465 IBinder token, String id, int requestCode,
1466 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001467 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001468 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1470 list.add(new ResultInfo(id, requestCode, resultCode, data));
1471 mAppThread.scheduleSendResult(token, list);
1472 }
1473
1474 // if the thread hasn't started yet, we don't have the handler, so just
1475 // save the messages until we're ready.
1476 private final void queueOrSendMessage(int what, Object obj) {
1477 queueOrSendMessage(what, obj, 0, 0);
1478 }
1479
1480 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1481 queueOrSendMessage(what, obj, arg1, 0);
1482 }
1483
1484 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1485 synchronized (this) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001486 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1488 + ": " + arg1 + " / " + obj);
1489 Message msg = Message.obtain();
1490 msg.what = what;
1491 msg.obj = obj;
1492 msg.arg1 = arg1;
1493 msg.arg2 = arg2;
1494 mH.sendMessage(msg);
1495 }
1496 }
1497
Dianne Hackborn21556372010-02-04 16:34:40 -08001498 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 String what) {
1500 ContextCleanupInfo cci = new ContextCleanupInfo();
1501 cci.context = context;
1502 cci.who = who;
1503 cci.what = what;
1504 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1505 }
1506
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001507 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1509
1510 ActivityInfo aInfo = r.activityInfo;
1511 if (r.packageInfo == null) {
1512 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1513 Context.CONTEXT_INCLUDE_CODE);
1514 }
Bob Leee5408332009-09-04 18:31:17 -07001515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 ComponentName component = r.intent.getComponent();
1517 if (component == null) {
1518 component = r.intent.resolveActivity(
1519 mInitialApplication.getPackageManager());
1520 r.intent.setComponent(component);
1521 }
1522
1523 if (r.activityInfo.targetActivity != null) {
1524 component = new ComponentName(r.activityInfo.packageName,
1525 r.activityInfo.targetActivity);
1526 }
1527
1528 Activity activity = null;
1529 try {
1530 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1531 activity = mInstrumentation.newActivity(
1532 cl, component.getClassName(), r.intent);
1533 r.intent.setExtrasClassLoader(cl);
1534 if (r.state != null) {
1535 r.state.setClassLoader(cl);
1536 }
1537 } catch (Exception e) {
1538 if (!mInstrumentation.onException(activity, e)) {
1539 throw new RuntimeException(
1540 "Unable to instantiate activity " + component
1541 + ": " + e.toString(), e);
1542 }
1543 }
1544
1545 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001546 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001547
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001548 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1549 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 TAG, r + ": app=" + app
1551 + ", appName=" + app.getPackageName()
1552 + ", pkg=" + r.packageInfo.getPackageName()
1553 + ", comp=" + r.intent.getComponent().toShortString()
1554 + ", dir=" + r.packageInfo.getAppDir());
1555
1556 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001557 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 appContext.init(r.packageInfo, r.token, this);
1559 appContext.setOuterContext(activity);
1560 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1561 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001562 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001563 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001564 activity.attach(appContext, this, getInstrumentation(), r.token,
1565 r.ident, app, r.intent, r.activityInfo, title, r.parent,
1566 r.embeddedID, r.lastNonConfigurationInstance,
1567 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001568
Christopher Tateb70f3df2009-04-07 16:07:59 -07001569 if (customIntent != null) {
1570 activity.mIntent = customIntent;
1571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 r.lastNonConfigurationInstance = null;
1573 r.lastNonConfigurationChildInstances = null;
1574 activity.mStartedActivity = false;
1575 int theme = r.activityInfo.getThemeResource();
1576 if (theme != 0) {
1577 activity.setTheme(theme);
1578 }
1579
1580 activity.mCalled = false;
1581 mInstrumentation.callActivityOnCreate(activity, r.state);
1582 if (!activity.mCalled) {
1583 throw new SuperNotCalledException(
1584 "Activity " + r.intent.getComponent().toShortString() +
1585 " did not call through to super.onCreate()");
1586 }
1587 r.activity = activity;
1588 r.stopped = true;
1589 if (!r.activity.mFinished) {
1590 activity.performStart();
1591 r.stopped = false;
1592 }
1593 if (!r.activity.mFinished) {
1594 if (r.state != null) {
1595 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1596 }
1597 }
1598 if (!r.activity.mFinished) {
1599 activity.mCalled = false;
1600 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1601 if (!activity.mCalled) {
1602 throw new SuperNotCalledException(
1603 "Activity " + r.intent.getComponent().toShortString() +
1604 " did not call through to super.onPostCreate()");
1605 }
1606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608 r.paused = true;
1609
1610 mActivities.put(r.token, r);
1611
1612 } catch (SuperNotCalledException e) {
1613 throw e;
1614
1615 } catch (Exception e) {
1616 if (!mInstrumentation.onException(activity, e)) {
1617 throw new RuntimeException(
1618 "Unable to start activity " + component
1619 + ": " + e.toString(), e);
1620 }
1621 }
1622
1623 return activity;
1624 }
1625
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001626 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 // If we are getting ready to gc after going to the background, well
1628 // we are back active so skip it.
1629 unscheduleGcIdler();
1630
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001631 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001633 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634
1635 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001636 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001637 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 handleResumeActivity(r.token, false, r.isForward);
1639
1640 if (!r.activity.mFinished && r.startsNotResumed) {
1641 // The activity manager actually wants this one to start out
1642 // paused, because it needs to be visible but isn't in the
1643 // foreground. We accomplish this by going through the
1644 // normal startup (because activities expect to go through
1645 // onResume() the first time they run, before their window
1646 // is displayed), and then pausing it. However, in this case
1647 // we do -not- need to do the full pause cycle (of freezing
1648 // and such) because the activity manager assumes it can just
1649 // retain the current state it has.
1650 try {
1651 r.activity.mCalled = false;
1652 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001653 // We need to keep around the original state, in case
1654 // we need to be created again.
1655 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 if (!r.activity.mCalled) {
1657 throw new SuperNotCalledException(
1658 "Activity " + r.intent.getComponent().toShortString() +
1659 " did not call through to super.onPause()");
1660 }
1661
1662 } catch (SuperNotCalledException e) {
1663 throw e;
1664
1665 } catch (Exception e) {
1666 if (!mInstrumentation.onException(r.activity, e)) {
1667 throw new RuntimeException(
1668 "Unable to pause activity "
1669 + r.intent.getComponent().toShortString()
1670 + ": " + e.toString(), e);
1671 }
1672 }
1673 r.paused = true;
1674 }
1675 } else {
1676 // If there was an error, for any reason, tell the activity
1677 // manager to stop us.
1678 try {
1679 ActivityManagerNative.getDefault()
1680 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1681 } catch (RemoteException ex) {
1682 }
1683 }
1684 }
1685
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001686 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 List<Intent> intents) {
1688 final int N = intents.size();
1689 for (int i=0; i<N; i++) {
1690 Intent intent = intents.get(i);
1691 intent.setExtrasClassLoader(r.activity.getClassLoader());
1692 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1693 }
1694 }
1695
1696 public final void performNewIntents(IBinder token,
1697 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001698 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 if (r != null) {
1700 final boolean resumed = !r.paused;
1701 if (resumed) {
1702 mInstrumentation.callActivityOnPause(r.activity);
1703 }
1704 deliverNewIntents(r, intents);
1705 if (resumed) {
1706 mInstrumentation.callActivityOnResume(r.activity);
1707 }
1708 }
1709 }
Bob Leee5408332009-09-04 18:31:17 -07001710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 private final void handleNewIntent(NewIntentData data) {
1712 performNewIntents(data.token, data.intents);
1713 }
1714
1715 private final void handleReceiver(ReceiverData data) {
1716 // If we are getting ready to gc after going to the background, well
1717 // we are back active so skip it.
1718 unscheduleGcIdler();
1719
1720 String component = data.intent.getComponent().getClassName();
1721
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001722 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 data.info.applicationInfo);
1724
1725 IActivityManager mgr = ActivityManagerNative.getDefault();
1726
1727 BroadcastReceiver receiver = null;
1728 try {
1729 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1730 data.intent.setExtrasClassLoader(cl);
1731 if (data.resultExtras != null) {
1732 data.resultExtras.setClassLoader(cl);
1733 }
1734 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1735 } catch (Exception e) {
1736 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001737 if (DEBUG_BROADCAST) Slog.i(TAG,
1738 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1740 data.resultData, data.resultExtras, data.resultAbort);
1741 } catch (RemoteException ex) {
1742 }
1743 throw new RuntimeException(
1744 "Unable to instantiate receiver " + component
1745 + ": " + e.toString(), e);
1746 }
1747
1748 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001749 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001750
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001751 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 TAG, "Performing receive of " + data.intent
1753 + ": app=" + app
1754 + ", appName=" + app.getPackageName()
1755 + ", pkg=" + packageInfo.getPackageName()
1756 + ", comp=" + data.intent.getComponent().toShortString()
1757 + ", dir=" + packageInfo.getAppDir());
1758
Dianne Hackborn21556372010-02-04 16:34:40 -08001759 ContextImpl context = (ContextImpl)app.getBaseContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 receiver.setOrderedHint(true);
1761 receiver.setResult(data.resultCode, data.resultData,
1762 data.resultExtras);
1763 receiver.setOrderedHint(data.sync);
1764 receiver.onReceive(context.getReceiverRestrictedContext(),
1765 data.intent);
1766 } catch (Exception e) {
1767 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001768 if (DEBUG_BROADCAST) Slog.i(TAG,
1769 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1771 data.resultData, data.resultExtras, data.resultAbort);
1772 } catch (RemoteException ex) {
1773 }
1774 if (!mInstrumentation.onException(receiver, e)) {
1775 throw new RuntimeException(
1776 "Unable to start receiver " + component
1777 + ": " + e.toString(), e);
1778 }
1779 }
1780
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001781 QueuedWork.waitToFinish();
1782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 try {
1784 if (data.sync) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001785 if (DEBUG_BROADCAST) Slog.i(TAG,
1786 "Finishing ordered broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 mgr.finishReceiver(
1788 mAppThread.asBinder(), receiver.getResultCode(),
1789 receiver.getResultData(), receiver.getResultExtras(false),
1790 receiver.getAbortBroadcast());
1791 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001792 if (DEBUG_BROADCAST) Slog.i(TAG,
1793 "Finishing broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
1795 }
1796 } catch (RemoteException ex) {
1797 }
1798 }
1799
Christopher Tate181fafa2009-05-14 11:12:14 -07001800 // Instantiate a BackupAgent and tell it that it's alive
1801 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001802 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001803
1804 // no longer idle; we have backup work to do
1805 unscheduleGcIdler();
1806
1807 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001808 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001809 String packageName = packageInfo.mPackageName;
1810 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001811 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001812 + " already exists");
1813 return;
1814 }
Bob Leee5408332009-09-04 18:31:17 -07001815
Christopher Tate181fafa2009-05-14 11:12:14 -07001816 BackupAgent agent = null;
1817 String classname = data.appInfo.backupAgentName;
1818 if (classname == null) {
1819 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001820 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001821 + packageName);
1822 return;
1823 }
1824 classname = "android.app.FullBackupAgent";
1825 }
1826 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001827 IBinder binder = null;
1828 try {
1829 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1830 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1831
1832 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001833 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001834 + data.appInfo.backupAgentName);
1835
Dianne Hackborn21556372010-02-04 16:34:40 -08001836 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001837 context.init(packageInfo, null, this);
1838 context.setOuterContext(agent);
1839 agent.attach(context);
1840
1841 agent.onCreate();
1842 binder = agent.onBind();
1843 mBackupAgents.put(packageName, agent);
1844 } catch (Exception e) {
1845 // If this is during restore, fail silently; otherwise go
1846 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001847 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001848 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1849 throw e;
1850 }
1851 // falling through with 'binder' still null
1852 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001853
1854 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001855 try {
1856 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1857 } catch (RemoteException e) {
1858 // nothing to do.
1859 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001860 } catch (Exception e) {
1861 throw new RuntimeException("Unable to create BackupAgent "
1862 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1863 }
1864 }
1865
1866 // Tear down a BackupAgent
1867 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001868 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001869
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001870 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001871 String packageName = packageInfo.mPackageName;
1872 BackupAgent agent = mBackupAgents.get(packageName);
1873 if (agent != null) {
1874 try {
1875 agent.onDestroy();
1876 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001877 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001878 e.printStackTrace();
1879 }
1880 mBackupAgents.remove(packageName);
1881 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001882 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001883 }
1884 }
1885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 private final void handleCreateService(CreateServiceData data) {
1887 // If we are getting ready to gc after going to the background, well
1888 // we are back active so skip it.
1889 unscheduleGcIdler();
1890
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001891 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 data.info.applicationInfo);
1893 Service service = null;
1894 try {
1895 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1896 service = (Service) cl.loadClass(data.info.name).newInstance();
1897 } catch (Exception e) {
1898 if (!mInstrumentation.onException(service, e)) {
1899 throw new RuntimeException(
1900 "Unable to instantiate service " + data.info.name
1901 + ": " + e.toString(), e);
1902 }
1903 }
1904
1905 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001906 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907
Dianne Hackborn21556372010-02-04 16:34:40 -08001908 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 context.init(packageInfo, null, this);
1910
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001911 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 context.setOuterContext(service);
1913 service.attach(context, this, data.info.name, data.token, app,
1914 ActivityManagerNative.getDefault());
1915 service.onCreate();
1916 mServices.put(data.token, service);
1917 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001918 ActivityManagerNative.getDefault().serviceDoneExecuting(
1919 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 } catch (RemoteException e) {
1921 // nothing to do.
1922 }
1923 } catch (Exception e) {
1924 if (!mInstrumentation.onException(service, e)) {
1925 throw new RuntimeException(
1926 "Unable to create service " + data.info.name
1927 + ": " + e.toString(), e);
1928 }
1929 }
1930 }
1931
1932 private final void handleBindService(BindServiceData data) {
1933 Service s = mServices.get(data.token);
1934 if (s != null) {
1935 try {
1936 data.intent.setExtrasClassLoader(s.getClassLoader());
1937 try {
1938 if (!data.rebind) {
1939 IBinder binder = s.onBind(data.intent);
1940 ActivityManagerNative.getDefault().publishService(
1941 data.token, data.intent, binder);
1942 } else {
1943 s.onRebind(data.intent);
1944 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001945 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001947 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 } catch (RemoteException ex) {
1949 }
1950 } catch (Exception e) {
1951 if (!mInstrumentation.onException(s, e)) {
1952 throw new RuntimeException(
1953 "Unable to bind to service " + s
1954 + " with " + data.intent + ": " + e.toString(), e);
1955 }
1956 }
1957 }
1958 }
1959
1960 private final void handleUnbindService(BindServiceData data) {
1961 Service s = mServices.get(data.token);
1962 if (s != null) {
1963 try {
1964 data.intent.setExtrasClassLoader(s.getClassLoader());
1965 boolean doRebind = s.onUnbind(data.intent);
1966 try {
1967 if (doRebind) {
1968 ActivityManagerNative.getDefault().unbindFinished(
1969 data.token, data.intent, doRebind);
1970 } else {
1971 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001972 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
1974 } catch (RemoteException ex) {
1975 }
1976 } catch (Exception e) {
1977 if (!mInstrumentation.onException(s, e)) {
1978 throw new RuntimeException(
1979 "Unable to unbind to service " + s
1980 + " with " + data.intent + ": " + e.toString(), e);
1981 }
1982 }
1983 }
1984 }
1985
1986 private void handleDumpService(DumpServiceInfo info) {
1987 try {
1988 Service s = mServices.get(info.service);
1989 if (s != null) {
1990 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
1991 s.dump(info.fd, pw, info.args);
1992 pw.close();
1993 }
1994 } finally {
1995 synchronized (info) {
1996 info.dumped = true;
1997 info.notifyAll();
1998 }
1999 }
2000 }
2001
2002 private final void handleServiceArgs(ServiceArgsData data) {
2003 Service s = mServices.get(data.token);
2004 if (s != null) {
2005 try {
2006 if (data.args != null) {
2007 data.args.setExtrasClassLoader(s.getClassLoader());
2008 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002009 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002010
2011 QueuedWork.waitToFinish();
2012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002014 ActivityManagerNative.getDefault().serviceDoneExecuting(
2015 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 } catch (RemoteException e) {
2017 // nothing to do.
2018 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002019 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 } catch (Exception e) {
2021 if (!mInstrumentation.onException(s, e)) {
2022 throw new RuntimeException(
2023 "Unable to start service " + s
2024 + " with " + data.args + ": " + e.toString(), e);
2025 }
2026 }
2027 }
2028 }
2029
2030 private final void handleStopService(IBinder token) {
2031 Service s = mServices.remove(token);
2032 if (s != null) {
2033 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002034 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 s.onDestroy();
2036 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002037 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002039 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002041
2042 QueuedWork.waitToFinish();
2043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002045 ActivityManagerNative.getDefault().serviceDoneExecuting(
2046 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 } catch (RemoteException e) {
2048 // nothing to do.
2049 }
2050 } catch (Exception e) {
2051 if (!mInstrumentation.onException(s, e)) {
2052 throw new RuntimeException(
2053 "Unable to stop service " + s
2054 + ": " + e.toString(), e);
2055 }
2056 }
2057 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002058 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
2060
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002061 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002063 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002064 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 + " finished=" + r.activity.mFinished);
2066 if (r != null && !r.activity.mFinished) {
2067 if (clearHide) {
2068 r.hideForNow = false;
2069 r.activity.mStartedActivity = false;
2070 }
2071 try {
2072 if (r.pendingIntents != null) {
2073 deliverNewIntents(r, r.pendingIntents);
2074 r.pendingIntents = null;
2075 }
2076 if (r.pendingResults != null) {
2077 deliverResults(r, r.pendingResults);
2078 r.pendingResults = null;
2079 }
2080 r.activity.performResume();
2081
Bob Leee5408332009-09-04 18:31:17 -07002082 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 r.paused = false;
2086 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 r.state = null;
2088 } catch (Exception e) {
2089 if (!mInstrumentation.onException(r.activity, e)) {
2090 throw new RuntimeException(
2091 "Unable to resume activity "
2092 + r.intent.getComponent().toShortString()
2093 + ": " + e.toString(), e);
2094 }
2095 }
2096 }
2097 return r;
2098 }
2099
2100 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2101 // If we are getting ready to gc after going to the background, well
2102 // we are back active so skip it.
2103 unscheduleGcIdler();
2104
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002105 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106
2107 if (r != null) {
2108 final Activity a = r.activity;
2109
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002110 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 TAG, "Resume " + r + " started activity: " +
2112 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2113 + ", finished: " + a.mFinished);
2114
2115 final int forwardBit = isForward ?
2116 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 // If the window hasn't yet been added to the window manager,
2119 // and this guy didn't finish itself or start another activity,
2120 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002121 boolean willBeVisible = !a.mStartedActivity;
2122 if (!willBeVisible) {
2123 try {
2124 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2125 a.getActivityToken());
2126 } catch (RemoteException e) {
2127 }
2128 }
2129 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 r.window = r.activity.getWindow();
2131 View decor = r.window.getDecorView();
2132 decor.setVisibility(View.INVISIBLE);
2133 ViewManager wm = a.getWindowManager();
2134 WindowManager.LayoutParams l = r.window.getAttributes();
2135 a.mDecor = decor;
2136 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2137 l.softInputMode |= forwardBit;
2138 if (a.mVisibleFromClient) {
2139 a.mWindowAdded = true;
2140 wm.addView(decor, l);
2141 }
2142
2143 // If the window has already been added, but during resume
2144 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002145 // window visible.
2146 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002147 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 TAG, "Launch " + r + " mStartedActivity set");
2149 r.hideForNow = true;
2150 }
2151
2152 // The window is now visible if it has been added, we are not
2153 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002154 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002155 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002157 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002158 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 performConfigurationChanged(r.activity, r.newConfig);
2160 r.newConfig = null;
2161 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002162 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 + isForward);
2164 WindowManager.LayoutParams l = r.window.getAttributes();
2165 if ((l.softInputMode
2166 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2167 != forwardBit) {
2168 l.softInputMode = (l.softInputMode
2169 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2170 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002171 if (r.activity.mVisibleFromClient) {
2172 ViewManager wm = a.getWindowManager();
2173 View decor = r.window.getDecorView();
2174 wm.updateViewLayout(decor, l);
2175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 }
2177 r.activity.mVisibleFromServer = true;
2178 mNumVisibleActivities++;
2179 if (r.activity.mVisibleFromClient) {
2180 r.activity.makeVisible();
2181 }
2182 }
2183
2184 r.nextIdle = mNewActivities;
2185 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002186 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 TAG, "Scheduling idle handler for " + r);
2188 Looper.myQueue().addIdleHandler(new Idler());
2189
2190 } else {
2191 // If an exception was thrown when trying to resume, then
2192 // just end this activity.
2193 try {
2194 ActivityManagerNative.getDefault()
2195 .finishActivity(token, Activity.RESULT_CANCELED, null);
2196 } catch (RemoteException ex) {
2197 }
2198 }
2199 }
2200
2201 private int mThumbnailWidth = -1;
2202 private int mThumbnailHeight = -1;
2203
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002204 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 Bitmap thumbnail = null;
2206 try {
2207 int w = mThumbnailWidth;
2208 int h;
2209 if (w < 0) {
2210 Resources res = r.activity.getResources();
2211 mThumbnailHeight = h =
2212 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2213
2214 mThumbnailWidth = w =
2215 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2216 } else {
2217 h = mThumbnailHeight;
2218 }
2219
Jim Miller0b2a6d02010-07-13 18:01:29 -07002220 // On platforms where we don't want thumbnails, set dims to (0,0)
2221 if ((w > 0) && (h > 0)) {
2222 View topView = r.activity.getWindow().getDecorView();
2223
2224 // Maximize bitmap by capturing in native aspect.
2225 if (topView.getWidth() >= topView.getHeight()) {
2226 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2227 } else {
2228 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2229 }
2230
2231 thumbnail.eraseColor(0);
2232 Canvas cv = new Canvas(thumbnail);
2233 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2234 thumbnail = null;
2235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 } catch (Exception e) {
2239 if (!mInstrumentation.onException(r.activity, e)) {
2240 throw new RuntimeException(
2241 "Unable to create thumbnail of "
2242 + r.intent.getComponent().toShortString()
2243 + ": " + e.toString(), e);
2244 }
2245 thumbnail = null;
2246 }
2247
2248 return thumbnail;
2249 }
2250
2251 private final void handlePauseActivity(IBinder token, boolean finished,
2252 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002253 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002255 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 if (userLeaving) {
2257 performUserLeavingActivity(r);
2258 }
Bob Leee5408332009-09-04 18:31:17 -07002259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 r.activity.mConfigChangeFlags |= configChanges;
2261 Bundle state = performPauseActivity(token, finished, true);
2262
2263 // Tell the activity manager we have paused.
2264 try {
2265 ActivityManagerNative.getDefault().activityPaused(token, state);
2266 } catch (RemoteException ex) {
2267 }
2268 }
2269 }
2270
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002271 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 mInstrumentation.callActivityOnUserLeaving(r.activity);
2273 }
2274
2275 final Bundle performPauseActivity(IBinder token, boolean finished,
2276 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002277 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 return r != null ? performPauseActivity(r, finished, saveState) : null;
2279 }
2280
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002281 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 boolean saveState) {
2283 if (r.paused) {
2284 if (r.activity.mFinished) {
2285 // If we are finishing, we won't call onResume() in certain cases.
2286 // So here we likewise don't want to call onPause() if the activity
2287 // isn't resumed.
2288 return null;
2289 }
2290 RuntimeException e = new RuntimeException(
2291 "Performing pause of activity that is not resumed: "
2292 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002293 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 }
2295 Bundle state = null;
2296 if (finished) {
2297 r.activity.mFinished = true;
2298 }
2299 try {
2300 // Next have the activity save its current state and managed dialogs...
2301 if (!r.activity.mFinished && saveState) {
2302 state = new Bundle();
2303 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2304 r.state = state;
2305 }
2306 // Now we are idle.
2307 r.activity.mCalled = false;
2308 mInstrumentation.callActivityOnPause(r.activity);
2309 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2310 if (!r.activity.mCalled) {
2311 throw new SuperNotCalledException(
2312 "Activity " + r.intent.getComponent().toShortString() +
2313 " did not call through to super.onPause()");
2314 }
2315
2316 } catch (SuperNotCalledException e) {
2317 throw e;
2318
2319 } catch (Exception e) {
2320 if (!mInstrumentation.onException(r.activity, e)) {
2321 throw new RuntimeException(
2322 "Unable to pause activity "
2323 + r.intent.getComponent().toShortString()
2324 + ": " + e.toString(), e);
2325 }
2326 }
2327 r.paused = true;
2328 return state;
2329 }
2330
2331 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002332 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 performStopActivityInner(r, null, false);
2334 }
2335
2336 private static class StopInfo {
2337 Bitmap thumbnail;
2338 CharSequence description;
2339 }
2340
2341 private final class ProviderRefCount {
2342 public int count;
2343 ProviderRefCount(int pCount) {
2344 count = pCount;
2345 }
2346 }
2347
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002348 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002350 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 if (r != null) {
2352 if (!keepShown && r.stopped) {
2353 if (r.activity.mFinished) {
2354 // If we are finishing, we won't call onResume() in certain
2355 // cases. So here we likewise don't want to call onStop()
2356 // if the activity isn't resumed.
2357 return;
2358 }
2359 RuntimeException e = new RuntimeException(
2360 "Performing stop of activity that is not resumed: "
2361 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002362 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 }
2364
2365 if (info != null) {
2366 try {
2367 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002368 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 info.description = r.activity.onCreateDescription();
2370 } catch (Exception e) {
2371 if (!mInstrumentation.onException(r.activity, e)) {
2372 throw new RuntimeException(
2373 "Unable to save state of activity "
2374 + r.intent.getComponent().toShortString()
2375 + ": " + e.toString(), e);
2376 }
2377 }
2378 }
2379
2380 if (!keepShown) {
2381 try {
2382 // Now we are idle.
2383 r.activity.performStop();
2384 } catch (Exception e) {
2385 if (!mInstrumentation.onException(r.activity, e)) {
2386 throw new RuntimeException(
2387 "Unable to stop activity "
2388 + r.intent.getComponent().toShortString()
2389 + ": " + e.toString(), e);
2390 }
2391 }
2392 r.stopped = true;
2393 }
2394
2395 r.paused = true;
2396 }
2397 }
2398
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002399 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 View v = r.activity.mDecor;
2401 if (v != null) {
2402 if (show) {
2403 if (!r.activity.mVisibleFromServer) {
2404 r.activity.mVisibleFromServer = true;
2405 mNumVisibleActivities++;
2406 if (r.activity.mVisibleFromClient) {
2407 r.activity.makeVisible();
2408 }
2409 }
2410 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002411 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002412 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 performConfigurationChanged(r.activity, r.newConfig);
2414 r.newConfig = null;
2415 }
2416 } else {
2417 if (r.activity.mVisibleFromServer) {
2418 r.activity.mVisibleFromServer = false;
2419 mNumVisibleActivities--;
2420 v.setVisibility(View.INVISIBLE);
2421 }
2422 }
2423 }
2424 }
2425
2426 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002427 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 r.activity.mConfigChangeFlags |= configChanges;
2429
2430 StopInfo info = new StopInfo();
2431 performStopActivityInner(r, info, show);
2432
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002433 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 TAG, "Finishing stop of " + r + ": show=" + show
2435 + " win=" + r.window);
2436
2437 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 // Tell activity manager we have been stopped.
2440 try {
2441 ActivityManagerNative.getDefault().activityStopped(
2442 r.token, info.thumbnail, info.description);
2443 } catch (RemoteException ex) {
2444 }
2445 }
2446
2447 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002448 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 if (r.stopped) {
2450 r.activity.performRestart();
2451 r.stopped = false;
2452 }
2453 }
2454
2455 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002456 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 if (!show && !r.stopped) {
2458 performStopActivityInner(r, null, show);
2459 } else if (show && r.stopped) {
2460 // If we are getting ready to gc after going to the background, well
2461 // we are back active so skip it.
2462 unscheduleGcIdler();
2463
2464 r.activity.performRestart();
2465 r.stopped = false;
2466 }
2467 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002468 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 TAG, "Handle window " + r + " visibility: " + show);
2470 updateVisibility(r, show);
2471 }
2472 }
2473
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002474 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 final int N = results.size();
2476 for (int i=0; i<N; i++) {
2477 ResultInfo ri = results.get(i);
2478 try {
2479 if (ri.mData != null) {
2480 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2481 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002482 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002483 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 r.activity.dispatchActivityResult(ri.mResultWho,
2485 ri.mRequestCode, ri.mResultCode, ri.mData);
2486 } catch (Exception e) {
2487 if (!mInstrumentation.onException(r.activity, e)) {
2488 throw new RuntimeException(
2489 "Failure delivering result " + ri + " to activity "
2490 + r.intent.getComponent().toShortString()
2491 + ": " + e.toString(), e);
2492 }
2493 }
2494 }
2495 }
2496
2497 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002498 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002499 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 if (r != null) {
2501 final boolean resumed = !r.paused;
2502 if (!r.activity.mFinished && r.activity.mDecor != null
2503 && r.hideForNow && resumed) {
2504 // We had hidden the activity because it started another
2505 // one... we have gotten a result back and we are not
2506 // paused, so make sure our window is visible.
2507 updateVisibility(r, true);
2508 }
2509 if (resumed) {
2510 try {
2511 // Now we are idle.
2512 r.activity.mCalled = false;
2513 mInstrumentation.callActivityOnPause(r.activity);
2514 if (!r.activity.mCalled) {
2515 throw new SuperNotCalledException(
2516 "Activity " + r.intent.getComponent().toShortString()
2517 + " did not call through to super.onPause()");
2518 }
2519 } catch (SuperNotCalledException e) {
2520 throw e;
2521 } catch (Exception e) {
2522 if (!mInstrumentation.onException(r.activity, e)) {
2523 throw new RuntimeException(
2524 "Unable to pause activity "
2525 + r.intent.getComponent().toShortString()
2526 + ": " + e.toString(), e);
2527 }
2528 }
2529 }
2530 deliverResults(r, res.results);
2531 if (resumed) {
2532 mInstrumentation.callActivityOnResume(r.activity);
2533 }
2534 }
2535 }
2536
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002537 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 return performDestroyActivity(token, finishing, 0, false);
2539 }
2540
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002541 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002543 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002544 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 if (r != null) {
2546 r.activity.mConfigChangeFlags |= configChanges;
2547 if (finishing) {
2548 r.activity.mFinished = true;
2549 }
2550 if (!r.paused) {
2551 try {
2552 r.activity.mCalled = false;
2553 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002554 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 r.activity.getComponentName().getClassName());
2556 if (!r.activity.mCalled) {
2557 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002558 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 + " did not call through to super.onPause()");
2560 }
2561 } catch (SuperNotCalledException e) {
2562 throw e;
2563 } catch (Exception e) {
2564 if (!mInstrumentation.onException(r.activity, e)) {
2565 throw new RuntimeException(
2566 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002567 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 + ": " + e.toString(), e);
2569 }
2570 }
2571 r.paused = true;
2572 }
2573 if (!r.stopped) {
2574 try {
2575 r.activity.performStop();
2576 } catch (SuperNotCalledException e) {
2577 throw e;
2578 } catch (Exception e) {
2579 if (!mInstrumentation.onException(r.activity, e)) {
2580 throw new RuntimeException(
2581 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002582 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 + ": " + e.toString(), e);
2584 }
2585 }
2586 r.stopped = true;
2587 }
2588 if (getNonConfigInstance) {
2589 try {
2590 r.lastNonConfigurationInstance
2591 = r.activity.onRetainNonConfigurationInstance();
2592 } catch (Exception e) {
2593 if (!mInstrumentation.onException(r.activity, e)) {
2594 throw new RuntimeException(
2595 "Unable to retain activity "
2596 + r.intent.getComponent().toShortString()
2597 + ": " + e.toString(), e);
2598 }
2599 }
2600 try {
2601 r.lastNonConfigurationChildInstances
2602 = r.activity.onRetainNonConfigurationChildInstances();
2603 } catch (Exception e) {
2604 if (!mInstrumentation.onException(r.activity, e)) {
2605 throw new RuntimeException(
2606 "Unable to retain child activities "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002607 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 + ": " + e.toString(), e);
2609 }
2610 }
Bob Leee5408332009-09-04 18:31:17 -07002611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 }
2613 try {
2614 r.activity.mCalled = false;
2615 r.activity.onDestroy();
2616 if (!r.activity.mCalled) {
2617 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002618 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 " did not call through to super.onDestroy()");
2620 }
2621 if (r.window != null) {
2622 r.window.closeAllPanels();
2623 }
2624 } catch (SuperNotCalledException e) {
2625 throw e;
2626 } catch (Exception e) {
2627 if (!mInstrumentation.onException(r.activity, e)) {
2628 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002629 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2630 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 }
2632 }
2633 }
2634 mActivities.remove(token);
2635
2636 return r;
2637 }
2638
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002639 private static String safeToComponentShortString(Intent intent) {
2640 ComponentName component = intent.getComponent();
2641 return component == null ? "[Unknown]" : component.toShortString();
2642 }
2643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 private final void handleDestroyActivity(IBinder token, boolean finishing,
2645 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002646 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 configChanges, getNonConfigInstance);
2648 if (r != null) {
2649 WindowManager wm = r.activity.getWindowManager();
2650 View v = r.activity.mDecor;
2651 if (v != null) {
2652 if (r.activity.mVisibleFromServer) {
2653 mNumVisibleActivities--;
2654 }
2655 IBinder wtoken = v.getWindowToken();
2656 if (r.activity.mWindowAdded) {
2657 wm.removeViewImmediate(v);
2658 }
2659 if (wtoken != null) {
2660 WindowManagerImpl.getDefault().closeAll(wtoken,
2661 r.activity.getClass().getName(), "Activity");
2662 }
2663 r.activity.mDecor = null;
2664 }
2665 WindowManagerImpl.getDefault().closeAll(token,
2666 r.activity.getClass().getName(), "Activity");
2667
2668 // Mocked out contexts won't be participating in the normal
2669 // process lifecycle, but if we're running with a proper
2670 // ApplicationContext we need to have it tear down things
2671 // cleanly.
2672 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002673 if (c instanceof ContextImpl) {
2674 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 r.activity.getClass().getName(), "Activity");
2676 }
2677 }
2678 if (finishing) {
2679 try {
2680 ActivityManagerNative.getDefault().activityDestroyed(token);
2681 } catch (RemoteException ex) {
2682 // If the system process has died, it's game over for everyone.
2683 }
2684 }
2685 }
2686
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002687 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 // If we are getting ready to gc after going to the background, well
2689 // we are back active so skip it.
2690 unscheduleGcIdler();
2691
2692 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002693
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002694 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002695 + tmp.token + " with configChanges=0x"
2696 + Integer.toHexString(configChanges));
2697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 // First: make sure we have the most recent configuration and most
2699 // recent version of the activity, or skip it if some previous call
2700 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002701 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 int N = mRelaunchingActivities.size();
2703 IBinder token = tmp.token;
2704 tmp = null;
2705 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002706 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 if (r.token == token) {
2708 tmp = r;
2709 mRelaunchingActivities.remove(i);
2710 i--;
2711 N--;
2712 }
2713 }
Bob Leee5408332009-09-04 18:31:17 -07002714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002716 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 return;
2718 }
Bob Leee5408332009-09-04 18:31:17 -07002719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 if (mPendingConfiguration != null) {
2721 changedConfig = mPendingConfiguration;
2722 mPendingConfiguration = null;
2723 }
2724 }
Bob Leee5408332009-09-04 18:31:17 -07002725
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002726 if (tmp.createdConfig != null) {
2727 // If the activity manager is passing us its current config,
2728 // assume that is really what we want regardless of what we
2729 // may have pending.
2730 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002731 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2732 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2733 if (changedConfig == null
2734 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2735 changedConfig = tmp.createdConfig;
2736 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002737 }
2738 }
2739
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002740 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002741 + tmp.token + ": changedConfig=" + changedConfig);
2742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 // If there was a pending configuration change, execute it first.
2744 if (changedConfig != null) {
2745 handleConfigurationChanged(changedConfig);
2746 }
Bob Leee5408332009-09-04 18:31:17 -07002747
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002748 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002749 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 if (r == null) {
2751 return;
2752 }
Bob Leee5408332009-09-04 18:31:17 -07002753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002755 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 Bundle savedState = null;
2758 if (!r.paused) {
2759 savedState = performPauseActivity(r.token, false, true);
2760 }
Bob Leee5408332009-09-04 18:31:17 -07002761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 r.activity = null;
2765 r.window = null;
2766 r.hideForNow = false;
2767 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002768 // Merge any pending results and pending intents; don't just replace them
2769 if (tmp.pendingResults != null) {
2770 if (r.pendingResults == null) {
2771 r.pendingResults = tmp.pendingResults;
2772 } else {
2773 r.pendingResults.addAll(tmp.pendingResults);
2774 }
2775 }
2776 if (tmp.pendingIntents != null) {
2777 if (r.pendingIntents == null) {
2778 r.pendingIntents = tmp.pendingIntents;
2779 } else {
2780 r.pendingIntents.addAll(tmp.pendingIntents);
2781 }
2782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 r.startsNotResumed = tmp.startsNotResumed;
2784 if (savedState != null) {
2785 r.state = savedState;
2786 }
Bob Leee5408332009-09-04 18:31:17 -07002787
Christopher Tateb70f3df2009-04-07 16:07:59 -07002788 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 }
2790
2791 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002792 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 Bitmap thumbnail = createThumbnailBitmap(r);
2794 CharSequence description = null;
2795 try {
2796 description = r.activity.onCreateDescription();
2797 } catch (Exception e) {
2798 if (!mInstrumentation.onException(r.activity, e)) {
2799 throw new RuntimeException(
2800 "Unable to create description of activity "
2801 + r.intent.getComponent().toShortString()
2802 + ": " + e.toString(), e);
2803 }
2804 }
2805 //System.out.println("Reporting top thumbnail " + thumbnail);
2806 try {
2807 ActivityManagerNative.getDefault().reportThumbnail(
2808 token, thumbnail, description);
2809 } catch (RemoteException ex) {
2810 }
2811 }
2812
2813 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2814 boolean allActivities, Configuration newConfig) {
2815 ArrayList<ComponentCallbacks> callbacks
2816 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002819 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002821 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 Activity a = ar.activity;
2823 if (a != null) {
2824 if (!ar.activity.mFinished && (allActivities ||
2825 (a != null && !ar.paused))) {
2826 // If the activity is currently resumed, its configuration
2827 // needs to change right now.
2828 callbacks.add(a);
2829 } else if (newConfig != null) {
2830 // Otherwise, we will tell it about the change
2831 // the next time it is resumed or shown. Note that
2832 // the activity manager may, before then, decide the
2833 // activity needs to be destroyed to handle its new
2834 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002835 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002836 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 ar.newConfig = newConfig;
2838 }
2839 }
2840 }
2841 }
2842 if (mServices.size() > 0) {
2843 Iterator<Service> it = mServices.values().iterator();
2844 while (it.hasNext()) {
2845 callbacks.add(it.next());
2846 }
2847 }
2848 synchronized (mProviderMap) {
2849 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002850 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 while (it.hasNext()) {
2852 callbacks.add(it.next().mLocalProvider);
2853 }
2854 }
2855 }
2856 final int N = mAllApplications.size();
2857 for (int i=0; i<N; i++) {
2858 callbacks.add(mAllApplications.get(i));
2859 }
Bob Leee5408332009-09-04 18:31:17 -07002860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 return callbacks;
2862 }
Bob Leee5408332009-09-04 18:31:17 -07002863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 private final void performConfigurationChanged(
2865 ComponentCallbacks cb, Configuration config) {
2866 // Only for Activity objects, check that they actually call up to their
2867 // superclass implementation. ComponentCallbacks is an interface, so
2868 // we check the runtime type and act accordingly.
2869 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2870 if (activity != null) {
2871 activity.mCalled = false;
2872 }
Bob Leee5408332009-09-04 18:31:17 -07002873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 boolean shouldChangeConfig = false;
2875 if ((activity == null) || (activity.mCurrentConfig == null)) {
2876 shouldChangeConfig = true;
2877 } else {
Bob Leee5408332009-09-04 18:31:17 -07002878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 // If the new config is the same as the config this Activity
2880 // is already running with then don't bother calling
2881 // onConfigurationChanged
2882 int diff = activity.mCurrentConfig.diff(config);
2883 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 // If this activity doesn't handle any of the config changes
2886 // then don't bother calling onConfigurationChanged as we're
2887 // going to destroy it.
2888 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2889 shouldChangeConfig = true;
2890 }
2891 }
2892 }
Bob Leee5408332009-09-04 18:31:17 -07002893
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002894 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002895 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 if (shouldChangeConfig) {
2897 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 if (activity != null) {
2900 if (!activity.mCalled) {
2901 throw new SuperNotCalledException(
2902 "Activity " + activity.getLocalClassName() +
2903 " did not call through to super.onConfigurationChanged()");
2904 }
2905 activity.mConfigChangeFlags = 0;
2906 activity.mCurrentConfig = new Configuration(config);
2907 }
2908 }
2909 }
2910
Dianne Hackbornae078162010-03-18 11:29:37 -07002911 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002912 if (mResConfiguration == null) {
2913 mResConfiguration = new Configuration();
2914 }
2915 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002916 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002917 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002918 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002919 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002920 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002921 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002922
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002923 // set it for java, this also affects newly created Resources
2924 if (config.locale != null) {
2925 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 }
Bob Leee5408332009-09-04 18:31:17 -07002927
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002928 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07002929
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002930 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002931 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002932
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002933 Iterator<WeakReference<Resources>> it =
2934 mActiveResources.values().iterator();
2935 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
2936 // mActiveResources.entrySet().iterator();
2937 while (it.hasNext()) {
2938 WeakReference<Resources> v = it.next();
2939 Resources r = v.get();
2940 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002941 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002942 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002943 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002944 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002945 // + " " + r + ": " + r.getConfiguration());
2946 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002947 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002948 it.remove();
2949 }
2950 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002951
2952 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002953 }
2954
2955 final void handleConfigurationChanged(Configuration config) {
2956
2957 ArrayList<ComponentCallbacks> callbacks = null;
2958
2959 synchronized (mPackages) {
2960 if (mPendingConfiguration != null) {
2961 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
2962 config = mPendingConfiguration;
2963 }
2964 mPendingConfiguration = null;
2965 }
2966
2967 if (config == null) {
2968 return;
2969 }
2970
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002971 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002972 + config);
2973
2974 applyConfigurationToResourcesLocked(config);
2975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 if (mConfiguration == null) {
2977 mConfiguration = new Configuration();
2978 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002979 if (!mConfiguration.isOtherSeqNewer(config)) {
2980 return;
2981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07002983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 callbacks = collectComponentCallbacksLocked(false, config);
2985 }
Bob Leee5408332009-09-04 18:31:17 -07002986
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002987 if (callbacks != null) {
2988 final int N = callbacks.size();
2989 for (int i=0; i<N; i++) {
2990 performConfigurationChanged(callbacks.get(i), config);
2991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 }
2993 }
2994
2995 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002996 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 if (r == null || r.activity == null) {
2998 return;
2999 }
Bob Leee5408332009-09-04 18:31:17 -07003000
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003001 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003002 + r.activityInfo.name);
3003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 performConfigurationChanged(r.activity, mConfiguration);
3005 }
3006
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003007 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003008 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003009 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003010 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3011 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003012 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003013 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003014 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003015 } finally {
3016 try {
3017 pcd.fd.close();
3018 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003019 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003020 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003021 }
3022 } else {
3023 Debug.stopMethodTracing();
3024 }
3025 }
Bob Leee5408332009-09-04 18:31:17 -07003026
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003027 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3028 boolean hasPkgInfo = false;
3029 if (packages != null) {
3030 for (int i=packages.length-1; i>=0; i--) {
3031 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3032 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003033 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003034 ref = mPackages.get(packages[i]);
3035 if (ref != null && ref.get() != null) {
3036 hasPkgInfo = true;
3037 } else {
3038 ref = mResourcePackages.get(packages[i]);
3039 if (ref != null && ref.get() != null) {
3040 hasPkgInfo = true;
3041 }
3042 }
3043 }
3044 mPackages.remove(packages[i]);
3045 mResourcePackages.remove(packages[i]);
3046 }
3047 }
3048 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3049 hasPkgInfo);
3050 }
3051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 final void handleLowMemory() {
3053 ArrayList<ComponentCallbacks> callbacks
3054 = new ArrayList<ComponentCallbacks>();
3055
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003056 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 callbacks = collectComponentCallbacksLocked(true, null);
3058 }
Bob Leee5408332009-09-04 18:31:17 -07003059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 final int N = callbacks.size();
3061 for (int i=0; i<N; i++) {
3062 callbacks.get(i).onLowMemory();
3063 }
3064
Chris Tatece229052009-03-25 16:44:52 -07003065 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3066 if (Process.myUid() != Process.SYSTEM_UID) {
3067 int sqliteReleased = SQLiteDatabase.releaseMemory();
3068 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3069 }
Bob Leee5408332009-09-04 18:31:17 -07003070
Mike Reedcaf0df12009-04-27 14:32:05 -04003071 // Ask graphics to free up as much as possible (font/image caches)
3072 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073
3074 BinderInternal.forceGc("mem");
3075 }
3076
3077 private final void handleBindApplication(AppBindData data) {
3078 mBoundApplication = data;
3079 mConfiguration = new Configuration(data.config);
3080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003082 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 android.ddm.DdmHandleAppName.setAppName(data.processName);
3084
3085 /*
3086 * Before spawning a new process, reset the time zone to be the system time zone.
3087 * This needs to be done because the system time zone could have changed after the
3088 * the spawning of this process. Without doing this this process would have the incorrect
3089 * system time zone.
3090 */
3091 TimeZone.setDefault(null);
3092
3093 /*
3094 * Initialize the default locale in this process for the reasons we set the time zone.
3095 */
3096 Locale.setDefault(data.config.locale);
3097
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003098 /*
3099 * Update the system configuration since its preloaded and might not
3100 * reflect configuration changes. The configuration object passed
3101 * in AppBindData can be safely assumed to be up to date
3102 */
3103 Resources.getSystem().updateConfiguration(mConfiguration, null);
3104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 data.info = getPackageInfoNoCheck(data.appInfo);
3106
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003107 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003108 * For system applications on userdebug/eng builds, log stack
3109 * traces of disk and network access to dropbox for analysis.
3110 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003111 if ((data.appInfo.flags &
3112 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003113 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3114 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003115 }
3116
3117 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003118 * Switch this process to density compatibility mode if needed.
3119 */
3120 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3121 == 0) {
3122 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3123 }
Bob Leee5408332009-09-04 18:31:17 -07003124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3126 // XXX should have option to change the port.
3127 Debug.changeDebugPort(8100);
3128 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003129 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 + " is waiting for the debugger on port 8100...");
3131
3132 IActivityManager mgr = ActivityManagerNative.getDefault();
3133 try {
3134 mgr.showWaitingForDebugger(mAppThread, true);
3135 } catch (RemoteException ex) {
3136 }
3137
3138 Debug.waitForDebugger();
3139
3140 try {
3141 mgr.showWaitingForDebugger(mAppThread, false);
3142 } catch (RemoteException ex) {
3143 }
3144
3145 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003146 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 + " can be debugged on port 8100...");
3148 }
3149 }
3150
3151 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003152 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 appContext.init(data.info, null, this);
3154 InstrumentationInfo ii = null;
3155 try {
3156 ii = appContext.getPackageManager().
3157 getInstrumentationInfo(data.instrumentationName, 0);
3158 } catch (PackageManager.NameNotFoundException e) {
3159 }
3160 if (ii == null) {
3161 throw new RuntimeException(
3162 "Unable to find instrumentation info for: "
3163 + data.instrumentationName);
3164 }
3165
3166 mInstrumentationAppDir = ii.sourceDir;
3167 mInstrumentationAppPackage = ii.packageName;
3168 mInstrumentedAppDir = data.info.getAppDir();
3169
3170 ApplicationInfo instrApp = new ApplicationInfo();
3171 instrApp.packageName = ii.packageName;
3172 instrApp.sourceDir = ii.sourceDir;
3173 instrApp.publicSourceDir = ii.publicSourceDir;
3174 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003175 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003176 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003178 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 instrContext.init(pi, null, this);
3180
3181 try {
3182 java.lang.ClassLoader cl = instrContext.getClassLoader();
3183 mInstrumentation = (Instrumentation)
3184 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3185 } catch (Exception e) {
3186 throw new RuntimeException(
3187 "Unable to instantiate instrumentation "
3188 + data.instrumentationName + ": " + e.toString(), e);
3189 }
3190
3191 mInstrumentation.init(this, instrContext, appContext,
3192 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3193
3194 if (data.profileFile != null && !ii.handleProfiling) {
3195 data.handlingProfiling = true;
3196 File file = new File(data.profileFile);
3197 file.getParentFile().mkdirs();
3198 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3199 }
3200
3201 try {
3202 mInstrumentation.onCreate(data.instrumentationArgs);
3203 }
3204 catch (Exception e) {
3205 throw new RuntimeException(
3206 "Exception thrown in onCreate() of "
3207 + data.instrumentationName + ": " + e.toString(), e);
3208 }
3209
3210 } else {
3211 mInstrumentation = new Instrumentation();
3212 }
3213
Christopher Tate181fafa2009-05-14 11:12:14 -07003214 // If the app is being launched for full backup or restore, bring it up in
3215 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003216 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 mInitialApplication = app;
3218
3219 List<ProviderInfo> providers = data.providers;
3220 if (providers != null) {
3221 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003222 // For process that contain content providers, we want to
3223 // ensure that the JIT is enabled "at some point".
3224 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 }
3226
3227 try {
3228 mInstrumentation.callApplicationOnCreate(app);
3229 } catch (Exception e) {
3230 if (!mInstrumentation.onException(app, e)) {
3231 throw new RuntimeException(
3232 "Unable to create application " + app.getClass().getName()
3233 + ": " + e.toString(), e);
3234 }
3235 }
3236 }
3237
3238 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3239 IActivityManager am = ActivityManagerNative.getDefault();
3240 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3241 Debug.stopMethodTracing();
3242 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003243 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 // + ", app thr: " + mAppThread);
3245 try {
3246 am.finishInstrumentation(mAppThread, resultCode, results);
3247 } catch (RemoteException ex) {
3248 }
3249 }
3250
3251 private final void installContentProviders(
3252 Context context, List<ProviderInfo> providers) {
3253 final ArrayList<IActivityManager.ContentProviderHolder> results =
3254 new ArrayList<IActivityManager.ContentProviderHolder>();
3255
3256 Iterator<ProviderInfo> i = providers.iterator();
3257 while (i.hasNext()) {
3258 ProviderInfo cpi = i.next();
3259 StringBuilder buf = new StringBuilder(128);
3260 buf.append("Publishing provider ");
3261 buf.append(cpi.authority);
3262 buf.append(": ");
3263 buf.append(cpi.name);
3264 Log.i(TAG, buf.toString());
3265 IContentProvider cp = installProvider(context, null, cpi, false);
3266 if (cp != null) {
3267 IActivityManager.ContentProviderHolder cph =
3268 new IActivityManager.ContentProviderHolder(cpi);
3269 cph.provider = cp;
3270 results.add(cph);
3271 // Don't ever unload this provider from the process.
3272 synchronized(mProviderMap) {
3273 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3274 }
3275 }
3276 }
3277
3278 try {
3279 ActivityManagerNative.getDefault().publishContentProviders(
3280 getApplicationThread(), results);
3281 } catch (RemoteException ex) {
3282 }
3283 }
3284
3285 private final IContentProvider getProvider(Context context, String name) {
3286 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003287 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 if (pr != null) {
3289 return pr.mProvider;
3290 }
3291 }
3292
3293 IActivityManager.ContentProviderHolder holder = null;
3294 try {
3295 holder = ActivityManagerNative.getDefault().getContentProvider(
3296 getApplicationThread(), name);
3297 } catch (RemoteException ex) {
3298 }
3299 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003300 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 return null;
3302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303
3304 IContentProvider prov = installProvider(context, holder.provider,
3305 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003306 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 if (holder.noReleaseNeeded || holder.provider == null) {
3308 // We are not going to release the provider if it is an external
3309 // provider that doesn't care about being released, or if it is
3310 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003311 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 synchronized(mProviderMap) {
3313 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3314 }
3315 }
3316 return prov;
3317 }
3318
3319 public final IContentProvider acquireProvider(Context c, String name) {
3320 IContentProvider provider = getProvider(c, name);
3321 if(provider == null)
3322 return null;
3323 IBinder jBinder = provider.asBinder();
3324 synchronized(mProviderMap) {
3325 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3326 if(prc == null) {
3327 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3328 } else {
3329 prc.count++;
3330 } //end else
3331 } //end synchronized
3332 return provider;
3333 }
3334
3335 public final boolean releaseProvider(IContentProvider provider) {
3336 if(provider == null) {
3337 return false;
3338 }
3339 IBinder jBinder = provider.asBinder();
3340 synchronized(mProviderMap) {
3341 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3342 if(prc == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003343 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldnt be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 return false;
3345 } else {
3346 prc.count--;
3347 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003348 // Schedule the actual remove asynchronously, since we
3349 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003350 // TODO: it would be nice to post a delayed message, so
3351 // if we come back and need the same provider quickly
3352 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003353 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3354 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 } //end if
3356 } //end else
3357 } //end synchronized
3358 return true;
3359 }
3360
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003361 final void completeRemoveProvider(IContentProvider provider) {
3362 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003363 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003364 synchronized(mProviderMap) {
3365 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3366 if(prc != null && prc.count == 0) {
3367 mProviderRefCountMap.remove(jBinder);
3368 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003369 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003370 }
3371 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003372
3373 if (name != null) {
3374 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003375 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003376 "ActivityManagerNative.removeContentProvider(" + name);
3377 ActivityManagerNative.getDefault().removeContentProvider(
3378 getApplicationThread(), name);
3379 } catch (RemoteException e) {
3380 //do nothing content provider object is dead any way
3381 } //end catch
3382 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003383 }
3384
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003385 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003387 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 }
3389 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003391 String name = null;
3392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003394 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003396 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 IBinder myBinder = pr.mProvider.asBinder();
3398 if (myBinder == providerBinder) {
3399 //find if its published by this process itself
3400 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003401 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003402 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003404 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 "death recipient");
3406 //content provider is in another process
3407 myBinder.unlinkToDeath(pr, 0);
3408 iter.remove();
3409 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003410 if(name == null) {
3411 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 }
3413 } //end if myBinder
3414 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003415
3416 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 }
3418
3419 final void removeDeadProvider(String name, IContentProvider provider) {
3420 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003421 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003423 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003424 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003425 if (removed != null) {
3426 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 }
3429 }
3430 }
3431
3432 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003433 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003435 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003436 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003437 if (removed != null) {
3438 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 }
3441 }
3442
3443 private final IContentProvider installProvider(Context context,
3444 IContentProvider provider, ProviderInfo info, boolean noisy) {
3445 ContentProvider localProvider = null;
3446 if (provider == null) {
3447 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003448 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 + info.name);
3450 }
3451 Context c = null;
3452 ApplicationInfo ai = info.applicationInfo;
3453 if (context.getPackageName().equals(ai.packageName)) {
3454 c = context;
3455 } else if (mInitialApplication != null &&
3456 mInitialApplication.getPackageName().equals(ai.packageName)) {
3457 c = mInitialApplication;
3458 } else {
3459 try {
3460 c = context.createPackageContext(ai.packageName,
3461 Context.CONTEXT_INCLUDE_CODE);
3462 } catch (PackageManager.NameNotFoundException e) {
3463 }
3464 }
3465 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003466 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 ai.packageName +
3468 " while loading content provider " +
3469 info.name);
3470 return null;
3471 }
3472 try {
3473 final java.lang.ClassLoader cl = c.getClassLoader();
3474 localProvider = (ContentProvider)cl.
3475 loadClass(info.name).newInstance();
3476 provider = localProvider.getIContentProvider();
3477 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003478 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 info.name + " from sourceDir " +
3480 info.applicationInfo.sourceDir);
3481 return null;
3482 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003483 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 TAG, "Instantiating local provider " + info.name);
3485 // XXX Need to create the correct context for this provider.
3486 localProvider.attachInfo(c, info);
3487 } catch (java.lang.Exception e) {
3488 if (!mInstrumentation.onException(null, e)) {
3489 throw new RuntimeException(
3490 "Unable to get provider " + info.name
3491 + ": " + e.toString(), e);
3492 }
3493 return null;
3494 }
3495 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003496 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 + info.name);
3498 }
3499
3500 synchronized (mProviderMap) {
3501 // Cache the pointer for the remote provider.
3502 String names[] = PATTERN_SEMICOLON.split(info.authority);
3503 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003504 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 localProvider);
3506 try {
3507 provider.asBinder().linkToDeath(pr, 0);
3508 mProviderMap.put(names[i], pr);
3509 } catch (RemoteException e) {
3510 return null;
3511 }
3512 }
3513 if (localProvider != null) {
3514 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003515 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 }
3517 }
3518
3519 return provider;
3520 }
3521
3522 private final void attach(boolean system) {
3523 sThreadLocal.set(this);
3524 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003526 ViewRoot.addFirstDrawHandler(new Runnable() {
3527 public void run() {
3528 ensureJitEnabled();
3529 }
3530 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3532 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3533 IActivityManager mgr = ActivityManagerNative.getDefault();
3534 try {
3535 mgr.attachApplication(mAppThread);
3536 } catch (RemoteException ex) {
3537 }
3538 } else {
3539 // Don't set application object here -- if the system crashes,
3540 // we can't display an alert, we just want to die die die.
3541 android.ddm.DdmHandleAppName.setAppName("system_process");
3542 try {
3543 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003544 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 context.init(getSystemContext().mPackageInfo, null, this);
3546 Application app = Instrumentation.newApplication(Application.class, context);
3547 mAllApplications.add(app);
3548 mInitialApplication = app;
3549 app.onCreate();
3550 } catch (Exception e) {
3551 throw new RuntimeException(
3552 "Unable to instantiate Application():" + e.toString(), e);
3553 }
3554 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003555
3556 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3557 public void onConfigurationChanged(Configuration newConfig) {
3558 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003559 // We need to apply this change to the resources
3560 // immediately, because upon returning the view
3561 // hierarchy will be informed about it.
3562 if (applyConfigurationToResourcesLocked(newConfig)) {
3563 // This actually changed the resources! Tell
3564 // everyone about it.
3565 if (mPendingConfiguration == null ||
3566 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3567 mPendingConfiguration = newConfig;
3568
3569 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3570 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003571 }
3572 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003573 }
3574 public void onLowMemory() {
3575 }
3576 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 }
3578
3579 private final void detach()
3580 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 sThreadLocal.set(null);
3582 }
3583
3584 public static final ActivityThread systemMain() {
3585 ActivityThread thread = new ActivityThread();
3586 thread.attach(true);
3587 return thread;
3588 }
3589
3590 public final void installSystemProviders(List providers) {
3591 if (providers != null) {
3592 installContentProviders(mInitialApplication,
3593 (List<ProviderInfo>)providers);
3594 }
3595 }
3596
3597 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003598 SamplingProfilerIntegration.start();
3599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 Process.setArgV0("<pre-initialized>");
3601
3602 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003603 if (sMainThreadHandler == null) {
3604 sMainThreadHandler = new Handler();
3605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606
3607 ActivityThread thread = new ActivityThread();
3608 thread.attach(false);
3609
3610 Looper.loop();
3611
3612 if (Process.supportsProcesses()) {
3613 throw new RuntimeException("Main thread loop unexpectedly exited");
3614 }
3615
3616 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003617 String name = (thread.mInitialApplication != null)
3618 ? thread.mInitialApplication.getPackageName()
3619 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003620 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 }
3622}