blob: 659909678a986a0592c6229f97951efdc26e33e9 [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
102/**
103 * This manages the execution of the main thread in an
104 * application process, scheduling and executing activities,
105 * broadcasts, and other operations on it as the activity
106 * manager requests.
107 *
108 * {@hide}
109 */
110public final class ActivityThread {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700111 static final String TAG = "ActivityThread";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700113 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
114 static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700115 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700116 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700117 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
119 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
120 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
121 private static final int LOG_ON_PAUSE_CALLED = 30021;
122 private static final int LOG_ON_RESUME_CALLED = 30022;
123
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700124 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700125
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700126 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700128 final ApplicationThread mAppThread = new ApplicationThread();
129 final Looper mLooper = Looper.myLooper();
130 final H mH = new H();
131 final HashMap<IBinder, ActivityClientRecord> mActivities
132 = new HashMap<IBinder, ActivityClientRecord>();
133 // List of new activities (via ActivityRecord.nextIdle) that should
134 // be reported when next we idle.
135 ActivityClientRecord mNewActivities = null;
136 // Number of activities that are currently visible on-screen.
137 int mNumVisibleActivities = 0;
138 final HashMap<IBinder, Service> mServices
139 = new HashMap<IBinder, Service>();
140 AppBindData mBoundApplication;
141 Configuration mConfiguration;
142 Configuration mResConfiguration;
143 Application mInitialApplication;
144 final ArrayList<Application> mAllApplications
145 = new ArrayList<Application>();
146 // set of instantiated backup agents, keyed by package name
147 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
148 static final ThreadLocal sThreadLocal = new ThreadLocal();
149 Instrumentation mInstrumentation;
150 String mInstrumentationAppDir = null;
151 String mInstrumentationAppPackage = null;
152 String mInstrumentedAppDir = null;
153 boolean mSystemThread = false;
154 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700156 // These can be accessed by multiple threads; mPackages is the lock.
157 // XXX For now we keep around information about all packages we have
158 // seen, not removing entries from this map.
159 final HashMap<String, WeakReference<LoadedApk>> mPackages
160 = new HashMap<String, WeakReference<LoadedApk>>();
161 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
162 = new HashMap<String, WeakReference<LoadedApk>>();
163 Display mDisplay = null;
164 DisplayMetrics mDisplayMetrics = null;
165 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
166 = new HashMap<ResourcesKey, WeakReference<Resources> >();
167 final ArrayList<ActivityClientRecord> mRelaunchingActivities
168 = new ArrayList<ActivityClientRecord>();
169 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700171 // The lock of mProviderMap protects the following variables.
172 final HashMap<String, ProviderClientRecord> mProviderMap
173 = new HashMap<String, ProviderClientRecord>();
174 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
175 = new HashMap<IBinder, ProviderRefCount>();
176 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
177 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700179 final GcIdler mGcIdler = new GcIdler();
180 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700182 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700184 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 Intent intent;
186 Bundle state;
187 Activity activity;
188 Window window;
189 Activity parent;
190 String embeddedID;
191 Object lastNonConfigurationInstance;
192 HashMap<String,Object> lastNonConfigurationChildInstances;
193 boolean paused;
194 boolean stopped;
195 boolean hideForNow;
196 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700197 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700198 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
200 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700201 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
203 List<ResultInfo> pendingResults;
204 List<Intent> pendingIntents;
205
206 boolean startsNotResumed;
207 boolean isForward;
208
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700209 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 parent = null;
211 embeddedID = null;
212 paused = false;
213 stopped = false;
214 hideForNow = false;
215 nextIdle = null;
216 }
217
218 public String toString() {
219 ComponentName componentName = intent.getComponent();
220 return "ActivityRecord{"
221 + Integer.toHexString(System.identityHashCode(this))
222 + " token=" + token + " " + (componentName == null
223 ? "no component name" : componentName.toShortString())
224 + "}";
225 }
226 }
227
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700228 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 final String mName;
230 final IContentProvider mProvider;
231 final ContentProvider mLocalProvider;
232
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700233 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 ContentProvider localProvider) {
235 mName = name;
236 mProvider = provider;
237 mLocalProvider = localProvider;
238 }
239
240 public void binderDied() {
241 removeDeadProvider(mName, mProvider);
242 }
243 }
244
245 private static final class NewIntentData {
246 List<Intent> intents;
247 IBinder token;
248 public String toString() {
249 return "NewIntentData{intents=" + intents + " token=" + token + "}";
250 }
251 }
252
253 private static final class ReceiverData {
254 Intent intent;
255 ActivityInfo info;
256 int resultCode;
257 String resultData;
258 Bundle resultExtras;
259 boolean sync;
260 boolean resultAbort;
261 public String toString() {
262 return "ReceiverData{intent=" + intent + " packageName=" +
263 info.packageName + " resultCode=" + resultCode
264 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
265 }
266 }
267
Christopher Tate181fafa2009-05-14 11:12:14 -0700268 private static final class CreateBackupAgentData {
269 ApplicationInfo appInfo;
270 int backupMode;
271 public String toString() {
272 return "CreateBackupAgentData{appInfo=" + appInfo
273 + " backupAgent=" + appInfo.backupAgentName
274 + " mode=" + backupMode + "}";
275 }
276 }
Bob Leee5408332009-09-04 18:31:17 -0700277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 private static final class CreateServiceData {
279 IBinder token;
280 ServiceInfo info;
281 Intent intent;
282 public String toString() {
283 return "CreateServiceData{token=" + token + " className="
284 + info.name + " packageName=" + info.packageName
285 + " intent=" + intent + "}";
286 }
287 }
288
289 private static final class BindServiceData {
290 IBinder token;
291 Intent intent;
292 boolean rebind;
293 public String toString() {
294 return "BindServiceData{token=" + token + " intent=" + intent + "}";
295 }
296 }
297
298 private static final class ServiceArgsData {
299 IBinder token;
300 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700301 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 Intent args;
303 public String toString() {
304 return "ServiceArgsData{token=" + token + " startId=" + startId
305 + " args=" + args + "}";
306 }
307 }
308
309 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700310 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 String processName;
312 ApplicationInfo appInfo;
313 List<ProviderInfo> providers;
314 ComponentName instrumentationName;
315 String profileFile;
316 Bundle instrumentationArgs;
317 IInstrumentationWatcher instrumentationWatcher;
318 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700319 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 Configuration config;
321 boolean handlingProfiling;
322 public String toString() {
323 return "AppBindData{appInfo=" + appInfo + "}";
324 }
325 }
326
327 private static final class DumpServiceInfo {
328 FileDescriptor fd;
329 IBinder service;
330 String[] args;
331 boolean dumped;
332 }
333
334 private static final class ResultData {
335 IBinder token;
336 List<ResultInfo> results;
337 public String toString() {
338 return "ResultData{token=" + token + " results" + results + "}";
339 }
340 }
341
342 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800343 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 String what;
345 String who;
346 }
347
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700348 private static final class ProfilerControlData {
349 String path;
350 ParcelFileDescriptor fd;
351 }
352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 private final class ApplicationThread extends ApplicationThreadNative {
354 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
355 private static final String ONE_COUNT_COLUMN = "%17s %8d";
356 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Noric3849202010-03-09 10:47:25 -0800357 private static final String DB_INFO_FORMAT = " %8d %8d %10d %s";
Bob Leee5408332009-09-04 18:31:17 -0700358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 // Formatting for checkin service - update version if row format changes
360 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 public final void schedulePauseActivity(IBinder token, boolean finished,
363 boolean userLeaving, int configChanges) {
364 queueOrSendMessage(
365 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
366 token,
367 (userLeaving ? 1 : 0),
368 configChanges);
369 }
370
371 public final void scheduleStopActivity(IBinder token, boolean showWindow,
372 int configChanges) {
373 queueOrSendMessage(
374 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
375 token, 0, configChanges);
376 }
377
378 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
379 queueOrSendMessage(
380 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
381 token);
382 }
383
384 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
385 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
386 }
387
388 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
389 ResultData res = new ResultData();
390 res.token = token;
391 res.results = results;
392 queueOrSendMessage(H.SEND_RESULT, res);
393 }
394
395 // we use token to identify this activity without having to send the
396 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700397 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
399 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700400 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401
402 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700403 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 r.intent = intent;
405 r.activityInfo = info;
406 r.state = state;
407
408 r.pendingResults = pendingResults;
409 r.pendingIntents = pendingNewIntents;
410
411 r.startsNotResumed = notResumed;
412 r.isForward = isForward;
413
414 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
415 }
416
417 public final void scheduleRelaunchActivity(IBinder token,
418 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800419 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700420 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421
422 r.token = token;
423 r.pendingResults = pendingResults;
424 r.pendingIntents = pendingNewIntents;
425 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800426 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800428 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 mRelaunchingActivities.add(r);
430 }
Bob Leee5408332009-09-04 18:31:17 -0700431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
433 }
434
435 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
436 NewIntentData data = new NewIntentData();
437 data.intents = intents;
438 data.token = token;
439
440 queueOrSendMessage(H.NEW_INTENT, data);
441 }
442
443 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
444 int configChanges) {
445 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
446 configChanges);
447 }
448
449 public final void scheduleReceiver(Intent intent, ActivityInfo info,
450 int resultCode, String data, Bundle extras, boolean sync) {
451 ReceiverData r = new ReceiverData();
452
453 r.intent = intent;
454 r.info = info;
455 r.resultCode = resultCode;
456 r.resultData = data;
457 r.resultExtras = extras;
458 r.sync = sync;
459
460 queueOrSendMessage(H.RECEIVER, r);
461 }
462
Christopher Tate181fafa2009-05-14 11:12:14 -0700463 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
464 CreateBackupAgentData d = new CreateBackupAgentData();
465 d.appInfo = app;
466 d.backupMode = backupMode;
467
468 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
469 }
470
471 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
472 CreateBackupAgentData d = new CreateBackupAgentData();
473 d.appInfo = app;
474
475 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
476 }
477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 public final void scheduleCreateService(IBinder token,
479 ServiceInfo info) {
480 CreateServiceData s = new CreateServiceData();
481 s.token = token;
482 s.info = info;
483
484 queueOrSendMessage(H.CREATE_SERVICE, s);
485 }
486
487 public final void scheduleBindService(IBinder token, Intent intent,
488 boolean rebind) {
489 BindServiceData s = new BindServiceData();
490 s.token = token;
491 s.intent = intent;
492 s.rebind = rebind;
493
494 queueOrSendMessage(H.BIND_SERVICE, s);
495 }
496
497 public final void scheduleUnbindService(IBinder token, Intent intent) {
498 BindServiceData s = new BindServiceData();
499 s.token = token;
500 s.intent = intent;
501
502 queueOrSendMessage(H.UNBIND_SERVICE, s);
503 }
504
505 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700506 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 ServiceArgsData s = new ServiceArgsData();
508 s.token = token;
509 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700510 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 s.args = args;
512
513 queueOrSendMessage(H.SERVICE_ARGS, s);
514 }
515
516 public final void scheduleStopService(IBinder token) {
517 queueOrSendMessage(H.STOP_SERVICE, token);
518 }
519
520 public final void bindApplication(String processName,
521 ApplicationInfo appInfo, List<ProviderInfo> providers,
522 ComponentName instrumentationName, String profileFile,
523 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700524 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526
527 if (services != null) {
528 // Setup the service cache in the ServiceManager
529 ServiceManager.initServiceCache(services);
530 }
531
532 AppBindData data = new AppBindData();
533 data.processName = processName;
534 data.appInfo = appInfo;
535 data.providers = providers;
536 data.instrumentationName = instrumentationName;
537 data.profileFile = profileFile;
538 data.instrumentationArgs = instrumentationArgs;
539 data.instrumentationWatcher = instrumentationWatcher;
540 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700541 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 data.config = config;
543 queueOrSendMessage(H.BIND_APPLICATION, data);
544 }
545
546 public final void scheduleExit() {
547 queueOrSendMessage(H.EXIT_APPLICATION, null);
548 }
549
Christopher Tate5e1ab332009-09-01 20:32:49 -0700550 public final void scheduleSuicide() {
551 queueOrSendMessage(H.SUICIDE, null);
552 }
553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 public void requestThumbnail(IBinder token) {
555 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
556 }
557
558 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800559 synchronized (mPackages) {
560 if (mPendingConfiguration == null ||
561 mPendingConfiguration.isOtherSeqNewer(config)) {
562 mPendingConfiguration = config;
563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 }
565 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
566 }
567
568 public void updateTimeZone() {
569 TimeZone.setDefault(null);
570 }
571
572 public void processInBackground() {
573 mH.removeMessages(H.GC_WHEN_IDLE);
574 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
575 }
576
577 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
578 DumpServiceInfo data = new DumpServiceInfo();
579 data.fd = fd;
580 data.service = servicetoken;
581 data.args = args;
582 data.dumped = false;
583 queueOrSendMessage(H.DUMP_SERVICE, data);
584 synchronized (data) {
585 while (!data.dumped) {
586 try {
587 data.wait();
588 } catch (InterruptedException e) {
589 // no need to do anything here, we will keep waiting until
590 // dumped is set
591 }
592 }
593 }
594 }
595
596 // This function exists to make sure all receiver dispatching is
597 // correctly ordered, since these are one-way calls and the binder driver
598 // applies transaction ordering per object for such calls.
599 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700600 int resultCode, String dataStr, Bundle extras, boolean ordered,
601 boolean sticky) throws RemoteException {
602 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 }
Bob Leee5408332009-09-04 18:31:17 -0700604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 public void scheduleLowMemory() {
606 queueOrSendMessage(H.LOW_MEMORY, null);
607 }
608
609 public void scheduleActivityConfigurationChanged(IBinder token) {
610 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
611 }
612
613 public void requestPss() {
614 try {
615 ActivityManagerNative.getDefault().reportPss(this,
616 (int)Process.getPss(Process.myPid()));
617 } catch (RemoteException e) {
618 }
619 }
Bob Leee5408332009-09-04 18:31:17 -0700620
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700621 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
622 ProfilerControlData pcd = new ProfilerControlData();
623 pcd.path = path;
624 pcd.fd = fd;
625 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800626 }
627
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700628 public void setSchedulingGroup(int group) {
629 // Note: do this immediately, since going into the foreground
630 // should happen regardless of what pending work we have to do
631 // and the activity manager will wait for us to report back that
632 // we are done before sending us to the background.
633 try {
634 Process.setProcessGroup(Process.myPid(), group);
635 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800636 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700637 }
638 }
Bob Leee5408332009-09-04 18:31:17 -0700639
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700640 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
641 Debug.getMemoryInfo(outInfo);
642 }
Bob Leee5408332009-09-04 18:31:17 -0700643
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700644 public void dispatchPackageBroadcast(int cmd, String[] packages) {
645 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
646 }
647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 @Override
649 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
650 long nativeMax = Debug.getNativeHeapSize() / 1024;
651 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
652 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
653
654 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
655 Debug.getMemoryInfo(memInfo);
656
657 final int nativeShared = memInfo.nativeSharedDirty;
658 final int dalvikShared = memInfo.dalvikSharedDirty;
659 final int otherShared = memInfo.otherSharedDirty;
660
661 final int nativePrivate = memInfo.nativePrivateDirty;
662 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
663 final int otherPrivate = memInfo.otherPrivateDirty;
664
665 Runtime runtime = Runtime.getRuntime();
666
667 long dalvikMax = runtime.totalMemory() / 1024;
668 long dalvikFree = runtime.freeMemory() / 1024;
669 long dalvikAllocated = dalvikMax - dalvikFree;
670 long viewInstanceCount = ViewDebug.getViewInstanceCount();
671 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Dianne Hackborn21556372010-02-04 16:34:40 -0800672 long appContextInstanceCount = ContextImpl.getInstanceCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 long activityInstanceCount = Activity.getInstanceCount();
674 int globalAssetCount = AssetManager.getGlobalAssetCount();
675 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
676 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
677 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
678 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
679 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
680 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800681 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 // Check to see if we were called by checkin server. If so, print terse format.
684 boolean doCheckinFormat = false;
685 if (args != null) {
686 for (String arg : args) {
687 if ("-c".equals(arg)) doCheckinFormat = true;
688 }
689 }
Bob Leee5408332009-09-04 18:31:17 -0700690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 // For checkin, we print one long comma-separated list of values
692 if (doCheckinFormat) {
693 // NOTE: if you change anything significant below, also consider changing
694 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700695 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 // Header
699 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
700 pw.print(Process.myPid()); pw.print(',');
701 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 // Heap info - max
704 pw.print(nativeMax); pw.print(',');
705 pw.print(dalvikMax); pw.print(',');
706 pw.print("N/A,");
707 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 // Heap info - allocated
710 pw.print(nativeAllocated); pw.print(',');
711 pw.print(dalvikAllocated); pw.print(',');
712 pw.print("N/A,");
713 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 // Heap info - free
716 pw.print(nativeFree); pw.print(',');
717 pw.print(dalvikFree); pw.print(',');
718 pw.print("N/A,");
719 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 // Heap info - proportional set size
722 pw.print(memInfo.nativePss); pw.print(',');
723 pw.print(memInfo.dalvikPss); pw.print(',');
724 pw.print(memInfo.otherPss); pw.print(',');
725 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700728 pw.print(nativeShared); pw.print(',');
729 pw.print(dalvikShared); pw.print(',');
730 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700734 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 pw.print(dalvikPrivate); pw.print(',');
736 pw.print(otherPrivate); pw.print(',');
737 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 // Object counts
740 pw.print(viewInstanceCount); pw.print(',');
741 pw.print(viewRootInstanceCount); pw.print(',');
742 pw.print(appContextInstanceCount); pw.print(',');
743 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 pw.print(globalAssetCount); pw.print(',');
746 pw.print(globalAssetManagerCount); pw.print(',');
747 pw.print(binderLocalObjectCount); pw.print(',');
748 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 pw.print(binderDeathObjectCount); pw.print(',');
751 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 // SQL
754 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800755 pw.print(stats.memoryUsed / 1024); pw.print(',');
756 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
757 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
758 for (int i = 0; i < stats.dbStats.size(); i++) {
759 DbStats dbStats = stats.dbStats.get(i);
760 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
761 dbStats.lookaside, dbStats.dbName);
762 pw.print(',');
763 }
Bob Leee5408332009-09-04 18:31:17 -0700764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 return;
766 }
Bob Leee5408332009-09-04 18:31:17 -0700767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 // otherwise, show human-readable format
769 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
770 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
771 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
772 nativeAllocated + dalvikAllocated);
773 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
774 nativeFree + dalvikFree);
775
776 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
777 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
778
779 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
780 nativeShared + dalvikShared + otherShared);
781 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
782 nativePrivate + dalvikPrivate + otherPrivate);
783
784 pw.println(" ");
785 pw.println(" Objects");
786 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
787 viewRootInstanceCount);
788
789 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
790 "Activities:", activityInstanceCount);
791
792 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
793 "AssetManagers:", globalAssetManagerCount);
794
795 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
796 "Proxy Binders:", binderProxyObjectCount);
797 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
798
799 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 // SQLite mem info
802 pw.println(" ");
803 pw.println(" SQL");
Vasu Noric3849202010-03-09 10:47:25 -0800804 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "memoryUsed:",
805 stats.memoryUsed / 1024);
806 printRow(pw, TWO_COUNT_COLUMNS, "pageCacheOverflo:", stats.pageCacheOverflo / 1024,
807 "largestMemAlloc:", stats.largestMemAlloc / 1024);
808 pw.println(" ");
809 int N = stats.dbStats.size();
810 if (N > 0) {
811 pw.println(" DATABASES");
812 printRow(pw, " %8s %8s %10s %s", "Pagesize", "Dbsize", "Lookaside", "Dbname");
813 for (int i = 0; i < N; i++) {
814 DbStats dbStats = stats.dbStats.get(i);
815 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
816 dbStats.lookaside, dbStats.dbName);
817 }
818 }
Bob Leee5408332009-09-04 18:31:17 -0700819
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700820 // Asset details.
821 String assetAlloc = AssetManager.getAssetAllocations();
822 if (assetAlloc != null) {
823 pw.println(" ");
824 pw.println(" Asset Allocations");
825 pw.print(assetAlloc);
826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 }
828
829 private void printRow(PrintWriter pw, String format, Object...objs) {
830 pw.println(String.format(format, objs));
831 }
832 }
833
834 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -0700835 private H() {
836 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
837 }
838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 public static final int LAUNCH_ACTIVITY = 100;
840 public static final int PAUSE_ACTIVITY = 101;
841 public static final int PAUSE_ACTIVITY_FINISHING= 102;
842 public static final int STOP_ACTIVITY_SHOW = 103;
843 public static final int STOP_ACTIVITY_HIDE = 104;
844 public static final int SHOW_WINDOW = 105;
845 public static final int HIDE_WINDOW = 106;
846 public static final int RESUME_ACTIVITY = 107;
847 public static final int SEND_RESULT = 108;
848 public static final int DESTROY_ACTIVITY = 109;
849 public static final int BIND_APPLICATION = 110;
850 public static final int EXIT_APPLICATION = 111;
851 public static final int NEW_INTENT = 112;
852 public static final int RECEIVER = 113;
853 public static final int CREATE_SERVICE = 114;
854 public static final int SERVICE_ARGS = 115;
855 public static final int STOP_SERVICE = 116;
856 public static final int REQUEST_THUMBNAIL = 117;
857 public static final int CONFIGURATION_CHANGED = 118;
858 public static final int CLEAN_UP_CONTEXT = 119;
859 public static final int GC_WHEN_IDLE = 120;
860 public static final int BIND_SERVICE = 121;
861 public static final int UNBIND_SERVICE = 122;
862 public static final int DUMP_SERVICE = 123;
863 public static final int LOW_MEMORY = 124;
864 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
865 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800866 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700867 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700868 public static final int DESTROY_BACKUP_AGENT = 129;
869 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700870 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800871 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700872 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 String codeToString(int code) {
874 if (localLOGV) {
875 switch (code) {
876 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
877 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
878 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
879 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
880 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
881 case SHOW_WINDOW: return "SHOW_WINDOW";
882 case HIDE_WINDOW: return "HIDE_WINDOW";
883 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
884 case SEND_RESULT: return "SEND_RESULT";
885 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
886 case BIND_APPLICATION: return "BIND_APPLICATION";
887 case EXIT_APPLICATION: return "EXIT_APPLICATION";
888 case NEW_INTENT: return "NEW_INTENT";
889 case RECEIVER: return "RECEIVER";
890 case CREATE_SERVICE: return "CREATE_SERVICE";
891 case SERVICE_ARGS: return "SERVICE_ARGS";
892 case STOP_SERVICE: return "STOP_SERVICE";
893 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
894 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
895 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
896 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
897 case BIND_SERVICE: return "BIND_SERVICE";
898 case UNBIND_SERVICE: return "UNBIND_SERVICE";
899 case DUMP_SERVICE: return "DUMP_SERVICE";
900 case LOW_MEMORY: return "LOW_MEMORY";
901 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
902 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800903 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700904 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
905 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700906 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700907 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800908 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700909 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911 }
912 return "(unknown)";
913 }
914 public void handleMessage(Message msg) {
915 switch (msg.what) {
916 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700917 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918
919 r.packageInfo = getPackageInfoNoCheck(
920 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700921 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 } break;
923 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700924 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 handleRelaunchActivity(r, msg.arg1);
926 } break;
927 case PAUSE_ACTIVITY:
928 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700929 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 break;
931 case PAUSE_ACTIVITY_FINISHING:
932 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
933 break;
934 case STOP_ACTIVITY_SHOW:
935 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
936 break;
937 case STOP_ACTIVITY_HIDE:
938 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
939 break;
940 case SHOW_WINDOW:
941 handleWindowVisibility((IBinder)msg.obj, true);
942 break;
943 case HIDE_WINDOW:
944 handleWindowVisibility((IBinder)msg.obj, false);
945 break;
946 case RESUME_ACTIVITY:
947 handleResumeActivity((IBinder)msg.obj, true,
948 msg.arg1 != 0);
949 break;
950 case SEND_RESULT:
951 handleSendResult((ResultData)msg.obj);
952 break;
953 case DESTROY_ACTIVITY:
954 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
955 msg.arg2, false);
956 break;
957 case BIND_APPLICATION:
958 AppBindData data = (AppBindData)msg.obj;
959 handleBindApplication(data);
960 break;
961 case EXIT_APPLICATION:
962 if (mInitialApplication != null) {
963 mInitialApplication.onTerminate();
964 }
965 Looper.myLooper().quit();
966 break;
967 case NEW_INTENT:
968 handleNewIntent((NewIntentData)msg.obj);
969 break;
970 case RECEIVER:
971 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700972 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 break;
974 case CREATE_SERVICE:
975 handleCreateService((CreateServiceData)msg.obj);
976 break;
977 case BIND_SERVICE:
978 handleBindService((BindServiceData)msg.obj);
979 break;
980 case UNBIND_SERVICE:
981 handleUnbindService((BindServiceData)msg.obj);
982 break;
983 case SERVICE_ARGS:
984 handleServiceArgs((ServiceArgsData)msg.obj);
985 break;
986 case STOP_SERVICE:
987 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700988 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 break;
990 case REQUEST_THUMBNAIL:
991 handleRequestThumbnail((IBinder)msg.obj);
992 break;
993 case CONFIGURATION_CHANGED:
994 handleConfigurationChanged((Configuration)msg.obj);
995 break;
996 case CLEAN_UP_CONTEXT:
997 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
998 cci.context.performFinalCleanup(cci.who, cci.what);
999 break;
1000 case GC_WHEN_IDLE:
1001 scheduleGcIdler();
1002 break;
1003 case DUMP_SERVICE:
1004 handleDumpService((DumpServiceInfo)msg.obj);
1005 break;
1006 case LOW_MEMORY:
1007 handleLowMemory();
1008 break;
1009 case ACTIVITY_CONFIGURATION_CHANGED:
1010 handleActivityConfigurationChanged((IBinder)msg.obj);
1011 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001012 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001013 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001014 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001015 case CREATE_BACKUP_AGENT:
1016 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1017 break;
1018 case DESTROY_BACKUP_AGENT:
1019 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1020 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001021 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001022 Process.killProcess(Process.myPid());
1023 break;
1024 case REMOVE_PROVIDER:
1025 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001026 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001027 case ENABLE_JIT:
1028 ensureJitEnabled();
1029 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001030 case DISPATCH_PACKAGE_BROADCAST:
1031 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1032 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 }
1034 }
Bob Leee5408332009-09-04 18:31:17 -07001035
1036 void maybeSnapshot() {
1037 if (mBoundApplication != null) {
1038 SamplingProfilerIntegration.writeSnapshot(
1039 mBoundApplication.processName);
1040 }
1041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043
1044 private final class Idler implements MessageQueue.IdleHandler {
1045 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001046 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 if (a != null) {
1048 mNewActivities = null;
1049 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001050 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001052 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 TAG, "Reporting idle of " + a +
1054 " finished=" +
1055 (a.activity != null ? a.activity.mFinished : false));
1056 if (a.activity != null && !a.activity.mFinished) {
1057 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001058 am.activityIdle(a.token, a.createdConfig);
1059 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 } catch (RemoteException ex) {
1061 }
1062 }
1063 prev = a;
1064 a = a.nextIdle;
1065 prev.nextIdle = null;
1066 } while (a != null);
1067 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001068 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 return false;
1070 }
1071 }
1072
1073 final class GcIdler implements MessageQueue.IdleHandler {
1074 public final boolean queueIdle() {
1075 doGcIfNeeded();
1076 return false;
1077 }
1078 }
1079
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001080 private final static class ResourcesKey {
1081 final private String mResDir;
1082 final private float mScale;
1083 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001084
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001085 ResourcesKey(String resDir, float scale) {
1086 mResDir = resDir;
1087 mScale = scale;
1088 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1089 }
Bob Leee5408332009-09-04 18:31:17 -07001090
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001091 @Override
1092 public int hashCode() {
1093 return mHash;
1094 }
1095
1096 @Override
1097 public boolean equals(Object obj) {
1098 if (!(obj instanceof ResourcesKey)) {
1099 return false;
1100 }
1101 ResourcesKey peer = (ResourcesKey) obj;
1102 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1103 }
1104 }
1105
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001106 public static final ActivityThread currentActivityThread() {
1107 return (ActivityThread)sThreadLocal.get();
1108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001110 public static final String currentPackageName() {
1111 ActivityThread am = currentActivityThread();
1112 return (am != null && am.mBoundApplication != null)
1113 ? am.mBoundApplication.processName : null;
1114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001116 public static final Application currentApplication() {
1117 ActivityThread am = currentActivityThread();
1118 return am != null ? am.mInitialApplication : null;
1119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001121 public static IPackageManager getPackageManager() {
1122 if (sPackageManager != null) {
1123 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1124 return sPackageManager;
1125 }
1126 IBinder b = ServiceManager.getService("package");
1127 //Slog.v("PackageManager", "default service binder = " + b);
1128 sPackageManager = IPackageManager.Stub.asInterface(b);
1129 //Slog.v("PackageManager", "default service = " + sPackageManager);
1130 return sPackageManager;
1131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001133 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1134 if (mDisplayMetrics != null && !forceUpdate) {
1135 return mDisplayMetrics;
1136 }
1137 if (mDisplay == null) {
1138 WindowManager wm = WindowManagerImpl.getDefault();
1139 mDisplay = wm.getDefaultDisplay();
1140 }
1141 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1142 mDisplay.getMetrics(metrics);
1143 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1144 // + metrics.heightPixels + " den=" + metrics.density
1145 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1146 return metrics;
1147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001149 /**
1150 * Creates the top level Resources for applications with the given compatibility info.
1151 *
1152 * @param resDir the resource directory.
1153 * @param compInfo the compability info. It will use the default compatibility info when it's
1154 * null.
1155 */
1156 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1157 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1158 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001160 // Resources is app scale dependent.
1161 if (false) {
1162 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1163 + compInfo.applicationScale);
1164 }
1165 WeakReference<Resources> wr = mActiveResources.get(key);
1166 r = wr != null ? wr.get() : null;
1167 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1168 if (r != null && r.getAssets().isUpToDate()) {
1169 if (false) {
1170 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1171 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1172 }
1173 return r;
1174 }
1175 }
1176
1177 //if (r != null) {
1178 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1179 // + r + " " + resDir);
1180 //}
1181
1182 AssetManager assets = new AssetManager();
1183 if (assets.addAssetPath(resDir) == 0) {
1184 return null;
1185 }
1186
1187 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1188 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1189 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1190 if (false) {
1191 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1192 + r.getConfiguration() + " appScale="
1193 + r.getCompatibilityInfo().applicationScale);
1194 }
1195
1196 synchronized (mPackages) {
1197 WeakReference<Resources> wr = mActiveResources.get(key);
1198 Resources existing = wr != null ? wr.get() : null;
1199 if (existing != null && existing.getAssets().isUpToDate()) {
1200 // Someone else already created the resources while we were
1201 // unlocked; go ahead and use theirs.
1202 r.getAssets().close();
1203 return existing;
1204 }
1205
1206 // XXX need to remove entries when weak references go away
1207 mActiveResources.put(key, new WeakReference<Resources>(r));
1208 return r;
1209 }
1210 }
1211
1212 /**
1213 * Creates the top level resources for the given package.
1214 */
1215 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1216 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1217 }
1218
1219 final Handler getHandler() {
1220 return mH;
1221 }
1222
1223 public final LoadedApk getPackageInfo(String packageName, int flags) {
1224 synchronized (mPackages) {
1225 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1227 ref = mPackages.get(packageName);
1228 } else {
1229 ref = mResourcePackages.get(packageName);
1230 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001231 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001232 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001233 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1234 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 if (packageInfo != null && (packageInfo.mResources == null
1236 || packageInfo.mResources.getAssets().isUpToDate())) {
1237 if (packageInfo.isSecurityViolation()
1238 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1239 throw new SecurityException(
1240 "Requesting code from " + packageName
1241 + " to be run in process "
1242 + mBoundApplication.processName
1243 + "/" + mBoundApplication.appInfo.uid);
1244 }
1245 return packageInfo;
1246 }
1247 }
1248
1249 ApplicationInfo ai = null;
1250 try {
1251 ai = getPackageManager().getApplicationInfo(packageName,
1252 PackageManager.GET_SHARED_LIBRARY_FILES);
1253 } catch (RemoteException e) {
1254 }
1255
1256 if (ai != null) {
1257 return getPackageInfo(ai, flags);
1258 }
1259
1260 return null;
1261 }
1262
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001263 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1265 boolean securityViolation = includeCode && ai.uid != 0
1266 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1267 ? ai.uid != mBoundApplication.appInfo.uid : true);
1268 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1269 |Context.CONTEXT_IGNORE_SECURITY))
1270 == Context.CONTEXT_INCLUDE_CODE) {
1271 if (securityViolation) {
1272 String msg = "Requesting code from " + ai.packageName
1273 + " (with uid " + ai.uid + ")";
1274 if (mBoundApplication != null) {
1275 msg = msg + " to be run in process "
1276 + mBoundApplication.processName + " (with uid "
1277 + mBoundApplication.appInfo.uid + ")";
1278 }
1279 throw new SecurityException(msg);
1280 }
1281 }
1282 return getPackageInfo(ai, null, securityViolation, includeCode);
1283 }
1284
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001285 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 return getPackageInfo(ai, null, false, true);
1287 }
1288
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001289 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1291 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001292 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 if (includeCode) {
1294 ref = mPackages.get(aInfo.packageName);
1295 } else {
1296 ref = mResourcePackages.get(aInfo.packageName);
1297 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001298 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 if (packageInfo == null || (packageInfo.mResources != null
1300 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001301 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 : "Loading resource-only package ") + aInfo.packageName
1303 + " (in " + (mBoundApplication != null
1304 ? mBoundApplication.processName : null)
1305 + ")");
1306 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001307 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 securityViolation, includeCode &&
1309 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1310 if (includeCode) {
1311 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001312 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 } else {
1314 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001315 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 }
1317 }
1318 return packageInfo;
1319 }
1320 }
1321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 ActivityThread() {
1323 }
1324
1325 public ApplicationThread getApplicationThread()
1326 {
1327 return mAppThread;
1328 }
1329
1330 public Instrumentation getInstrumentation()
1331 {
1332 return mInstrumentation;
1333 }
1334
1335 public Configuration getConfiguration() {
1336 return mConfiguration;
1337 }
1338
1339 public boolean isProfiling() {
1340 return mBoundApplication != null && mBoundApplication.profileFile != null;
1341 }
1342
1343 public String getProfileFilePath() {
1344 return mBoundApplication.profileFile;
1345 }
1346
1347 public Looper getLooper() {
1348 return mLooper;
1349 }
1350
1351 public Application getApplication() {
1352 return mInitialApplication;
1353 }
Bob Leee5408332009-09-04 18:31:17 -07001354
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001355 public String getProcessName() {
1356 return mBoundApplication.processName;
1357 }
Bob Leee5408332009-09-04 18:31:17 -07001358
Dianne Hackborn21556372010-02-04 16:34:40 -08001359 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 synchronized (this) {
1361 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001362 ContextImpl context =
1363 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001364 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 context.init(info, null, this);
1366 context.getResources().updateConfiguration(
1367 getConfiguration(), getDisplayMetricsLocked(false));
1368 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001369 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 // + ": " + context.getResources().getConfiguration());
1371 }
1372 }
1373 return mSystemContext;
1374 }
1375
Mike Cleron432b7132009-09-24 15:28:29 -07001376 public void installSystemApplicationInfo(ApplicationInfo info) {
1377 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001378 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001379 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001380 }
1381 }
1382
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001383 void ensureJitEnabled() {
1384 if (!mJitEnabled) {
1385 mJitEnabled = true;
1386 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1387 }
1388 }
1389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 void scheduleGcIdler() {
1391 if (!mGcIdlerScheduled) {
1392 mGcIdlerScheduled = true;
1393 Looper.myQueue().addIdleHandler(mGcIdler);
1394 }
1395 mH.removeMessages(H.GC_WHEN_IDLE);
1396 }
1397
1398 void unscheduleGcIdler() {
1399 if (mGcIdlerScheduled) {
1400 mGcIdlerScheduled = false;
1401 Looper.myQueue().removeIdleHandler(mGcIdler);
1402 }
1403 mH.removeMessages(H.GC_WHEN_IDLE);
1404 }
1405
1406 void doGcIfNeeded() {
1407 mGcIdlerScheduled = false;
1408 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001409 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 // + "m now=" + now);
1411 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001412 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 BinderInternal.forceGc("bg");
1414 }
1415 }
1416
1417 public final ActivityInfo resolveActivityInfo(Intent intent) {
1418 ActivityInfo aInfo = intent.resolveActivityInfo(
1419 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1420 if (aInfo == null) {
1421 // Throw an exception.
1422 Instrumentation.checkStartActivityResult(
1423 IActivityManager.START_CLASS_NOT_FOUND, intent);
1424 }
1425 return aInfo;
1426 }
Bob Leee5408332009-09-04 18:31:17 -07001427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
1430 Object lastNonConfigurationInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001431 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001433 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 r.intent = intent;
1435 r.state = state;
1436 r.parent = parent;
1437 r.embeddedID = id;
1438 r.activityInfo = activityInfo;
1439 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
1440 if (localLOGV) {
1441 ComponentName compname = intent.getComponent();
1442 String name;
1443 if (compname != null) {
1444 name = compname.toShortString();
1445 } else {
1446 name = "(Intent " + intent + ").getComponent() returned null";
1447 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001448 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 + ", comp=" + name
1450 + ", token=" + token);
1451 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001452 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 }
1454
1455 public final Activity getActivity(IBinder token) {
1456 return mActivities.get(token).activity;
1457 }
1458
1459 public final void sendActivityResult(
1460 IBinder token, String id, int requestCode,
1461 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001462 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001463 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1465 list.add(new ResultInfo(id, requestCode, resultCode, data));
1466 mAppThread.scheduleSendResult(token, list);
1467 }
1468
1469 // if the thread hasn't started yet, we don't have the handler, so just
1470 // save the messages until we're ready.
1471 private final void queueOrSendMessage(int what, Object obj) {
1472 queueOrSendMessage(what, obj, 0, 0);
1473 }
1474
1475 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1476 queueOrSendMessage(what, obj, arg1, 0);
1477 }
1478
1479 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1480 synchronized (this) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001481 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1483 + ": " + arg1 + " / " + obj);
1484 Message msg = Message.obtain();
1485 msg.what = what;
1486 msg.obj = obj;
1487 msg.arg1 = arg1;
1488 msg.arg2 = arg2;
1489 mH.sendMessage(msg);
1490 }
1491 }
1492
Dianne Hackborn21556372010-02-04 16:34:40 -08001493 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 String what) {
1495 ContextCleanupInfo cci = new ContextCleanupInfo();
1496 cci.context = context;
1497 cci.who = who;
1498 cci.what = what;
1499 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1500 }
1501
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001502 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1504
1505 ActivityInfo aInfo = r.activityInfo;
1506 if (r.packageInfo == null) {
1507 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1508 Context.CONTEXT_INCLUDE_CODE);
1509 }
Bob Leee5408332009-09-04 18:31:17 -07001510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 ComponentName component = r.intent.getComponent();
1512 if (component == null) {
1513 component = r.intent.resolveActivity(
1514 mInitialApplication.getPackageManager());
1515 r.intent.setComponent(component);
1516 }
1517
1518 if (r.activityInfo.targetActivity != null) {
1519 component = new ComponentName(r.activityInfo.packageName,
1520 r.activityInfo.targetActivity);
1521 }
1522
1523 Activity activity = null;
1524 try {
1525 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1526 activity = mInstrumentation.newActivity(
1527 cl, component.getClassName(), r.intent);
1528 r.intent.setExtrasClassLoader(cl);
1529 if (r.state != null) {
1530 r.state.setClassLoader(cl);
1531 }
1532 } catch (Exception e) {
1533 if (!mInstrumentation.onException(activity, e)) {
1534 throw new RuntimeException(
1535 "Unable to instantiate activity " + component
1536 + ": " + e.toString(), e);
1537 }
1538 }
1539
1540 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001541 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001542
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001543 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1544 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 TAG, r + ": app=" + app
1546 + ", appName=" + app.getPackageName()
1547 + ", pkg=" + r.packageInfo.getPackageName()
1548 + ", comp=" + r.intent.getComponent().toShortString()
1549 + ", dir=" + r.packageInfo.getAppDir());
1550
1551 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001552 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 appContext.init(r.packageInfo, r.token, this);
1554 appContext.setOuterContext(activity);
1555 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1556 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001557 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001558 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001559 activity.attach(appContext, this, getInstrumentation(), r.token,
1560 r.ident, app, r.intent, r.activityInfo, title, r.parent,
1561 r.embeddedID, r.lastNonConfigurationInstance,
1562 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001563
Christopher Tateb70f3df2009-04-07 16:07:59 -07001564 if (customIntent != null) {
1565 activity.mIntent = customIntent;
1566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 r.lastNonConfigurationInstance = null;
1568 r.lastNonConfigurationChildInstances = null;
1569 activity.mStartedActivity = false;
1570 int theme = r.activityInfo.getThemeResource();
1571 if (theme != 0) {
1572 activity.setTheme(theme);
1573 }
1574
1575 activity.mCalled = false;
1576 mInstrumentation.callActivityOnCreate(activity, r.state);
1577 if (!activity.mCalled) {
1578 throw new SuperNotCalledException(
1579 "Activity " + r.intent.getComponent().toShortString() +
1580 " did not call through to super.onCreate()");
1581 }
1582 r.activity = activity;
1583 r.stopped = true;
1584 if (!r.activity.mFinished) {
1585 activity.performStart();
1586 r.stopped = false;
1587 }
1588 if (!r.activity.mFinished) {
1589 if (r.state != null) {
1590 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1591 }
1592 }
1593 if (!r.activity.mFinished) {
1594 activity.mCalled = false;
1595 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1596 if (!activity.mCalled) {
1597 throw new SuperNotCalledException(
1598 "Activity " + r.intent.getComponent().toShortString() +
1599 " did not call through to super.onPostCreate()");
1600 }
1601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
1603 r.paused = true;
1604
1605 mActivities.put(r.token, r);
1606
1607 } catch (SuperNotCalledException e) {
1608 throw e;
1609
1610 } catch (Exception e) {
1611 if (!mInstrumentation.onException(activity, e)) {
1612 throw new RuntimeException(
1613 "Unable to start activity " + component
1614 + ": " + e.toString(), e);
1615 }
1616 }
1617
1618 return activity;
1619 }
1620
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001621 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 // If we are getting ready to gc after going to the background, well
1623 // we are back active so skip it.
1624 unscheduleGcIdler();
1625
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001626 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001628 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629
1630 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001631 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001632 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 handleResumeActivity(r.token, false, r.isForward);
1634
1635 if (!r.activity.mFinished && r.startsNotResumed) {
1636 // The activity manager actually wants this one to start out
1637 // paused, because it needs to be visible but isn't in the
1638 // foreground. We accomplish this by going through the
1639 // normal startup (because activities expect to go through
1640 // onResume() the first time they run, before their window
1641 // is displayed), and then pausing it. However, in this case
1642 // we do -not- need to do the full pause cycle (of freezing
1643 // and such) because the activity manager assumes it can just
1644 // retain the current state it has.
1645 try {
1646 r.activity.mCalled = false;
1647 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001648 // We need to keep around the original state, in case
1649 // we need to be created again.
1650 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (!r.activity.mCalled) {
1652 throw new SuperNotCalledException(
1653 "Activity " + r.intent.getComponent().toShortString() +
1654 " did not call through to super.onPause()");
1655 }
1656
1657 } catch (SuperNotCalledException e) {
1658 throw e;
1659
1660 } catch (Exception e) {
1661 if (!mInstrumentation.onException(r.activity, e)) {
1662 throw new RuntimeException(
1663 "Unable to pause activity "
1664 + r.intent.getComponent().toShortString()
1665 + ": " + e.toString(), e);
1666 }
1667 }
1668 r.paused = true;
1669 }
1670 } else {
1671 // If there was an error, for any reason, tell the activity
1672 // manager to stop us.
1673 try {
1674 ActivityManagerNative.getDefault()
1675 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1676 } catch (RemoteException ex) {
1677 }
1678 }
1679 }
1680
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001681 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 List<Intent> intents) {
1683 final int N = intents.size();
1684 for (int i=0; i<N; i++) {
1685 Intent intent = intents.get(i);
1686 intent.setExtrasClassLoader(r.activity.getClassLoader());
1687 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1688 }
1689 }
1690
1691 public final void performNewIntents(IBinder token,
1692 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001693 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 if (r != null) {
1695 final boolean resumed = !r.paused;
1696 if (resumed) {
1697 mInstrumentation.callActivityOnPause(r.activity);
1698 }
1699 deliverNewIntents(r, intents);
1700 if (resumed) {
1701 mInstrumentation.callActivityOnResume(r.activity);
1702 }
1703 }
1704 }
Bob Leee5408332009-09-04 18:31:17 -07001705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 private final void handleNewIntent(NewIntentData data) {
1707 performNewIntents(data.token, data.intents);
1708 }
1709
1710 private final void handleReceiver(ReceiverData data) {
1711 // If we are getting ready to gc after going to the background, well
1712 // we are back active so skip it.
1713 unscheduleGcIdler();
1714
1715 String component = data.intent.getComponent().getClassName();
1716
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001717 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 data.info.applicationInfo);
1719
1720 IActivityManager mgr = ActivityManagerNative.getDefault();
1721
1722 BroadcastReceiver receiver = null;
1723 try {
1724 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1725 data.intent.setExtrasClassLoader(cl);
1726 if (data.resultExtras != null) {
1727 data.resultExtras.setClassLoader(cl);
1728 }
1729 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1730 } catch (Exception e) {
1731 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001732 if (DEBUG_BROADCAST) Slog.i(TAG,
1733 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1735 data.resultData, data.resultExtras, data.resultAbort);
1736 } catch (RemoteException ex) {
1737 }
1738 throw new RuntimeException(
1739 "Unable to instantiate receiver " + component
1740 + ": " + e.toString(), e);
1741 }
1742
1743 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001744 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001745
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001746 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 TAG, "Performing receive of " + data.intent
1748 + ": app=" + app
1749 + ", appName=" + app.getPackageName()
1750 + ", pkg=" + packageInfo.getPackageName()
1751 + ", comp=" + data.intent.getComponent().toShortString()
1752 + ", dir=" + packageInfo.getAppDir());
1753
Dianne Hackborn21556372010-02-04 16:34:40 -08001754 ContextImpl context = (ContextImpl)app.getBaseContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 receiver.setOrderedHint(true);
1756 receiver.setResult(data.resultCode, data.resultData,
1757 data.resultExtras);
1758 receiver.setOrderedHint(data.sync);
1759 receiver.onReceive(context.getReceiverRestrictedContext(),
1760 data.intent);
1761 } catch (Exception e) {
1762 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001763 if (DEBUG_BROADCAST) Slog.i(TAG,
1764 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1766 data.resultData, data.resultExtras, data.resultAbort);
1767 } catch (RemoteException ex) {
1768 }
1769 if (!mInstrumentation.onException(receiver, e)) {
1770 throw new RuntimeException(
1771 "Unable to start receiver " + component
1772 + ": " + e.toString(), e);
1773 }
1774 }
1775
1776 try {
1777 if (data.sync) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001778 if (DEBUG_BROADCAST) Slog.i(TAG,
1779 "Finishing ordered broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 mgr.finishReceiver(
1781 mAppThread.asBinder(), receiver.getResultCode(),
1782 receiver.getResultData(), receiver.getResultExtras(false),
1783 receiver.getAbortBroadcast());
1784 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001785 if (DEBUG_BROADCAST) Slog.i(TAG,
1786 "Finishing broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
1788 }
1789 } catch (RemoteException ex) {
1790 }
1791 }
1792
Christopher Tate181fafa2009-05-14 11:12:14 -07001793 // Instantiate a BackupAgent and tell it that it's alive
1794 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001795 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001796
1797 // no longer idle; we have backup work to do
1798 unscheduleGcIdler();
1799
1800 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001801 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001802 String packageName = packageInfo.mPackageName;
1803 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001804 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001805 + " already exists");
1806 return;
1807 }
Bob Leee5408332009-09-04 18:31:17 -07001808
Christopher Tate181fafa2009-05-14 11:12:14 -07001809 BackupAgent agent = null;
1810 String classname = data.appInfo.backupAgentName;
1811 if (classname == null) {
1812 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001813 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001814 + packageName);
1815 return;
1816 }
1817 classname = "android.app.FullBackupAgent";
1818 }
1819 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001820 IBinder binder = null;
1821 try {
1822 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1823 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1824
1825 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001826 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001827 + data.appInfo.backupAgentName);
1828
Dianne Hackborn21556372010-02-04 16:34:40 -08001829 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001830 context.init(packageInfo, null, this);
1831 context.setOuterContext(agent);
1832 agent.attach(context);
1833
1834 agent.onCreate();
1835 binder = agent.onBind();
1836 mBackupAgents.put(packageName, agent);
1837 } catch (Exception e) {
1838 // If this is during restore, fail silently; otherwise go
1839 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001840 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001841 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1842 throw e;
1843 }
1844 // falling through with 'binder' still null
1845 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001846
1847 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001848 try {
1849 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1850 } catch (RemoteException e) {
1851 // nothing to do.
1852 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001853 } catch (Exception e) {
1854 throw new RuntimeException("Unable to create BackupAgent "
1855 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1856 }
1857 }
1858
1859 // Tear down a BackupAgent
1860 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001861 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001862
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001863 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001864 String packageName = packageInfo.mPackageName;
1865 BackupAgent agent = mBackupAgents.get(packageName);
1866 if (agent != null) {
1867 try {
1868 agent.onDestroy();
1869 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001870 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001871 e.printStackTrace();
1872 }
1873 mBackupAgents.remove(packageName);
1874 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001875 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001876 }
1877 }
1878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 private final void handleCreateService(CreateServiceData data) {
1880 // If we are getting ready to gc after going to the background, well
1881 // we are back active so skip it.
1882 unscheduleGcIdler();
1883
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001884 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 data.info.applicationInfo);
1886 Service service = null;
1887 try {
1888 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1889 service = (Service) cl.loadClass(data.info.name).newInstance();
1890 } catch (Exception e) {
1891 if (!mInstrumentation.onException(service, e)) {
1892 throw new RuntimeException(
1893 "Unable to instantiate service " + data.info.name
1894 + ": " + e.toString(), e);
1895 }
1896 }
1897
1898 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001899 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900
Dianne Hackborn21556372010-02-04 16:34:40 -08001901 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 context.init(packageInfo, null, this);
1903
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001904 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 context.setOuterContext(service);
1906 service.attach(context, this, data.info.name, data.token, app,
1907 ActivityManagerNative.getDefault());
1908 service.onCreate();
1909 mServices.put(data.token, service);
1910 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001911 ActivityManagerNative.getDefault().serviceDoneExecuting(
1912 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 } catch (RemoteException e) {
1914 // nothing to do.
1915 }
1916 } catch (Exception e) {
1917 if (!mInstrumentation.onException(service, e)) {
1918 throw new RuntimeException(
1919 "Unable to create service " + data.info.name
1920 + ": " + e.toString(), e);
1921 }
1922 }
1923 }
1924
1925 private final void handleBindService(BindServiceData data) {
1926 Service s = mServices.get(data.token);
1927 if (s != null) {
1928 try {
1929 data.intent.setExtrasClassLoader(s.getClassLoader());
1930 try {
1931 if (!data.rebind) {
1932 IBinder binder = s.onBind(data.intent);
1933 ActivityManagerNative.getDefault().publishService(
1934 data.token, data.intent, binder);
1935 } else {
1936 s.onRebind(data.intent);
1937 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001938 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001940 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 } catch (RemoteException ex) {
1942 }
1943 } catch (Exception e) {
1944 if (!mInstrumentation.onException(s, e)) {
1945 throw new RuntimeException(
1946 "Unable to bind to service " + s
1947 + " with " + data.intent + ": " + e.toString(), e);
1948 }
1949 }
1950 }
1951 }
1952
1953 private final void handleUnbindService(BindServiceData data) {
1954 Service s = mServices.get(data.token);
1955 if (s != null) {
1956 try {
1957 data.intent.setExtrasClassLoader(s.getClassLoader());
1958 boolean doRebind = s.onUnbind(data.intent);
1959 try {
1960 if (doRebind) {
1961 ActivityManagerNative.getDefault().unbindFinished(
1962 data.token, data.intent, doRebind);
1963 } else {
1964 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001965 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
1967 } catch (RemoteException ex) {
1968 }
1969 } catch (Exception e) {
1970 if (!mInstrumentation.onException(s, e)) {
1971 throw new RuntimeException(
1972 "Unable to unbind to service " + s
1973 + " with " + data.intent + ": " + e.toString(), e);
1974 }
1975 }
1976 }
1977 }
1978
1979 private void handleDumpService(DumpServiceInfo info) {
1980 try {
1981 Service s = mServices.get(info.service);
1982 if (s != null) {
1983 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
1984 s.dump(info.fd, pw, info.args);
1985 pw.close();
1986 }
1987 } finally {
1988 synchronized (info) {
1989 info.dumped = true;
1990 info.notifyAll();
1991 }
1992 }
1993 }
1994
1995 private final void handleServiceArgs(ServiceArgsData data) {
1996 Service s = mServices.get(data.token);
1997 if (s != null) {
1998 try {
1999 if (data.args != null) {
2000 data.args.setExtrasClassLoader(s.getClassLoader());
2001 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002002 int res = s.onStartCommand(data.args, data.flags, data.startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002004 ActivityManagerNative.getDefault().serviceDoneExecuting(
2005 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 } catch (RemoteException e) {
2007 // nothing to do.
2008 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002009 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 } catch (Exception e) {
2011 if (!mInstrumentation.onException(s, e)) {
2012 throw new RuntimeException(
2013 "Unable to start service " + s
2014 + " with " + data.args + ": " + e.toString(), e);
2015 }
2016 }
2017 }
2018 }
2019
2020 private final void handleStopService(IBinder token) {
2021 Service s = mServices.remove(token);
2022 if (s != null) {
2023 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002024 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 s.onDestroy();
2026 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002027 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002029 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
2031 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002032 ActivityManagerNative.getDefault().serviceDoneExecuting(
2033 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 } catch (RemoteException e) {
2035 // nothing to do.
2036 }
2037 } catch (Exception e) {
2038 if (!mInstrumentation.onException(s, e)) {
2039 throw new RuntimeException(
2040 "Unable to stop service " + s
2041 + ": " + e.toString(), e);
2042 }
2043 }
2044 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002045 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 }
2047
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002048 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002050 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002051 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 + " finished=" + r.activity.mFinished);
2053 if (r != null && !r.activity.mFinished) {
2054 if (clearHide) {
2055 r.hideForNow = false;
2056 r.activity.mStartedActivity = false;
2057 }
2058 try {
2059 if (r.pendingIntents != null) {
2060 deliverNewIntents(r, r.pendingIntents);
2061 r.pendingIntents = null;
2062 }
2063 if (r.pendingResults != null) {
2064 deliverResults(r, r.pendingResults);
2065 r.pendingResults = null;
2066 }
2067 r.activity.performResume();
2068
Bob Leee5408332009-09-04 18:31:17 -07002069 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 r.paused = false;
2073 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 r.state = null;
2075 } catch (Exception e) {
2076 if (!mInstrumentation.onException(r.activity, e)) {
2077 throw new RuntimeException(
2078 "Unable to resume activity "
2079 + r.intent.getComponent().toShortString()
2080 + ": " + e.toString(), e);
2081 }
2082 }
2083 }
2084 return r;
2085 }
2086
2087 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2088 // If we are getting ready to gc after going to the background, well
2089 // we are back active so skip it.
2090 unscheduleGcIdler();
2091
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002092 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093
2094 if (r != null) {
2095 final Activity a = r.activity;
2096
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002097 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 TAG, "Resume " + r + " started activity: " +
2099 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2100 + ", finished: " + a.mFinished);
2101
2102 final int forwardBit = isForward ?
2103 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 // If the window hasn't yet been added to the window manager,
2106 // and this guy didn't finish itself or start another activity,
2107 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002108 boolean willBeVisible = !a.mStartedActivity;
2109 if (!willBeVisible) {
2110 try {
2111 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2112 a.getActivityToken());
2113 } catch (RemoteException e) {
2114 }
2115 }
2116 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 r.window = r.activity.getWindow();
2118 View decor = r.window.getDecorView();
2119 decor.setVisibility(View.INVISIBLE);
2120 ViewManager wm = a.getWindowManager();
2121 WindowManager.LayoutParams l = r.window.getAttributes();
2122 a.mDecor = decor;
2123 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2124 l.softInputMode |= forwardBit;
2125 if (a.mVisibleFromClient) {
2126 a.mWindowAdded = true;
2127 wm.addView(decor, l);
2128 }
2129
2130 // If the window has already been added, but during resume
2131 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002132 // window visible.
2133 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002134 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 TAG, "Launch " + r + " mStartedActivity set");
2136 r.hideForNow = true;
2137 }
2138
2139 // The window is now visible if it has been added, we are not
2140 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002141 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002142 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002144 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002145 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 performConfigurationChanged(r.activity, r.newConfig);
2147 r.newConfig = null;
2148 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002149 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 + isForward);
2151 WindowManager.LayoutParams l = r.window.getAttributes();
2152 if ((l.softInputMode
2153 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2154 != forwardBit) {
2155 l.softInputMode = (l.softInputMode
2156 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2157 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002158 if (r.activity.mVisibleFromClient) {
2159 ViewManager wm = a.getWindowManager();
2160 View decor = r.window.getDecorView();
2161 wm.updateViewLayout(decor, l);
2162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 }
2164 r.activity.mVisibleFromServer = true;
2165 mNumVisibleActivities++;
2166 if (r.activity.mVisibleFromClient) {
2167 r.activity.makeVisible();
2168 }
2169 }
2170
2171 r.nextIdle = mNewActivities;
2172 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002173 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 TAG, "Scheduling idle handler for " + r);
2175 Looper.myQueue().addIdleHandler(new Idler());
2176
2177 } else {
2178 // If an exception was thrown when trying to resume, then
2179 // just end this activity.
2180 try {
2181 ActivityManagerNative.getDefault()
2182 .finishActivity(token, Activity.RESULT_CANCELED, null);
2183 } catch (RemoteException ex) {
2184 }
2185 }
2186 }
2187
2188 private int mThumbnailWidth = -1;
2189 private int mThumbnailHeight = -1;
2190
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002191 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 Bitmap thumbnail = null;
2193 try {
2194 int w = mThumbnailWidth;
2195 int h;
2196 if (w < 0) {
2197 Resources res = r.activity.getResources();
2198 mThumbnailHeight = h =
2199 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2200
2201 mThumbnailWidth = w =
2202 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2203 } else {
2204 h = mThumbnailHeight;
2205 }
2206
2207 // XXX Only set hasAlpha if needed?
2208 thumbnail = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
2209 thumbnail.eraseColor(0);
2210 Canvas cv = new Canvas(thumbnail);
2211 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2212 thumbnail = null;
2213 }
2214 } catch (Exception e) {
2215 if (!mInstrumentation.onException(r.activity, e)) {
2216 throw new RuntimeException(
2217 "Unable to create thumbnail of "
2218 + r.intent.getComponent().toShortString()
2219 + ": " + e.toString(), e);
2220 }
2221 thumbnail = null;
2222 }
2223
2224 return thumbnail;
2225 }
2226
2227 private final void handlePauseActivity(IBinder token, boolean finished,
2228 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002229 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002231 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 if (userLeaving) {
2233 performUserLeavingActivity(r);
2234 }
Bob Leee5408332009-09-04 18:31:17 -07002235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 r.activity.mConfigChangeFlags |= configChanges;
2237 Bundle state = performPauseActivity(token, finished, true);
2238
2239 // Tell the activity manager we have paused.
2240 try {
2241 ActivityManagerNative.getDefault().activityPaused(token, state);
2242 } catch (RemoteException ex) {
2243 }
2244 }
2245 }
2246
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002247 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 mInstrumentation.callActivityOnUserLeaving(r.activity);
2249 }
2250
2251 final Bundle performPauseActivity(IBinder token, boolean finished,
2252 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002253 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 return r != null ? performPauseActivity(r, finished, saveState) : null;
2255 }
2256
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002257 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 boolean saveState) {
2259 if (r.paused) {
2260 if (r.activity.mFinished) {
2261 // If we are finishing, we won't call onResume() in certain cases.
2262 // So here we likewise don't want to call onPause() if the activity
2263 // isn't resumed.
2264 return null;
2265 }
2266 RuntimeException e = new RuntimeException(
2267 "Performing pause of activity that is not resumed: "
2268 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002269 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 }
2271 Bundle state = null;
2272 if (finished) {
2273 r.activity.mFinished = true;
2274 }
2275 try {
2276 // Next have the activity save its current state and managed dialogs...
2277 if (!r.activity.mFinished && saveState) {
2278 state = new Bundle();
2279 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2280 r.state = state;
2281 }
2282 // Now we are idle.
2283 r.activity.mCalled = false;
2284 mInstrumentation.callActivityOnPause(r.activity);
2285 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2286 if (!r.activity.mCalled) {
2287 throw new SuperNotCalledException(
2288 "Activity " + r.intent.getComponent().toShortString() +
2289 " did not call through to super.onPause()");
2290 }
2291
2292 } catch (SuperNotCalledException e) {
2293 throw e;
2294
2295 } catch (Exception e) {
2296 if (!mInstrumentation.onException(r.activity, e)) {
2297 throw new RuntimeException(
2298 "Unable to pause activity "
2299 + r.intent.getComponent().toShortString()
2300 + ": " + e.toString(), e);
2301 }
2302 }
2303 r.paused = true;
2304 return state;
2305 }
2306
2307 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002308 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 performStopActivityInner(r, null, false);
2310 }
2311
2312 private static class StopInfo {
2313 Bitmap thumbnail;
2314 CharSequence description;
2315 }
2316
2317 private final class ProviderRefCount {
2318 public int count;
2319 ProviderRefCount(int pCount) {
2320 count = pCount;
2321 }
2322 }
2323
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002324 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002326 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 if (r != null) {
2328 if (!keepShown && r.stopped) {
2329 if (r.activity.mFinished) {
2330 // If we are finishing, we won't call onResume() in certain
2331 // cases. So here we likewise don't want to call onStop()
2332 // if the activity isn't resumed.
2333 return;
2334 }
2335 RuntimeException e = new RuntimeException(
2336 "Performing stop of activity that is not resumed: "
2337 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002338 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 }
2340
2341 if (info != null) {
2342 try {
2343 // First create a thumbnail for the activity...
2344 //info.thumbnail = createThumbnailBitmap(r);
2345 info.description = r.activity.onCreateDescription();
2346 } catch (Exception e) {
2347 if (!mInstrumentation.onException(r.activity, e)) {
2348 throw new RuntimeException(
2349 "Unable to save state of activity "
2350 + r.intent.getComponent().toShortString()
2351 + ": " + e.toString(), e);
2352 }
2353 }
2354 }
2355
2356 if (!keepShown) {
2357 try {
2358 // Now we are idle.
2359 r.activity.performStop();
2360 } catch (Exception e) {
2361 if (!mInstrumentation.onException(r.activity, e)) {
2362 throw new RuntimeException(
2363 "Unable to stop activity "
2364 + r.intent.getComponent().toShortString()
2365 + ": " + e.toString(), e);
2366 }
2367 }
2368 r.stopped = true;
2369 }
2370
2371 r.paused = true;
2372 }
2373 }
2374
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002375 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 View v = r.activity.mDecor;
2377 if (v != null) {
2378 if (show) {
2379 if (!r.activity.mVisibleFromServer) {
2380 r.activity.mVisibleFromServer = true;
2381 mNumVisibleActivities++;
2382 if (r.activity.mVisibleFromClient) {
2383 r.activity.makeVisible();
2384 }
2385 }
2386 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002387 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002388 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 performConfigurationChanged(r.activity, r.newConfig);
2390 r.newConfig = null;
2391 }
2392 } else {
2393 if (r.activity.mVisibleFromServer) {
2394 r.activity.mVisibleFromServer = false;
2395 mNumVisibleActivities--;
2396 v.setVisibility(View.INVISIBLE);
2397 }
2398 }
2399 }
2400 }
2401
2402 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002403 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 r.activity.mConfigChangeFlags |= configChanges;
2405
2406 StopInfo info = new StopInfo();
2407 performStopActivityInner(r, info, show);
2408
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002409 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 TAG, "Finishing stop of " + r + ": show=" + show
2411 + " win=" + r.window);
2412
2413 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 // Tell activity manager we have been stopped.
2416 try {
2417 ActivityManagerNative.getDefault().activityStopped(
2418 r.token, info.thumbnail, info.description);
2419 } catch (RemoteException ex) {
2420 }
2421 }
2422
2423 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002424 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 if (r.stopped) {
2426 r.activity.performRestart();
2427 r.stopped = false;
2428 }
2429 }
2430
2431 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002432 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 if (!show && !r.stopped) {
2434 performStopActivityInner(r, null, show);
2435 } else if (show && r.stopped) {
2436 // If we are getting ready to gc after going to the background, well
2437 // we are back active so skip it.
2438 unscheduleGcIdler();
2439
2440 r.activity.performRestart();
2441 r.stopped = false;
2442 }
2443 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002444 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 TAG, "Handle window " + r + " visibility: " + show);
2446 updateVisibility(r, show);
2447 }
2448 }
2449
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002450 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 final int N = results.size();
2452 for (int i=0; i<N; i++) {
2453 ResultInfo ri = results.get(i);
2454 try {
2455 if (ri.mData != null) {
2456 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2457 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002458 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002459 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 r.activity.dispatchActivityResult(ri.mResultWho,
2461 ri.mRequestCode, ri.mResultCode, ri.mData);
2462 } catch (Exception e) {
2463 if (!mInstrumentation.onException(r.activity, e)) {
2464 throw new RuntimeException(
2465 "Failure delivering result " + ri + " to activity "
2466 + r.intent.getComponent().toShortString()
2467 + ": " + e.toString(), e);
2468 }
2469 }
2470 }
2471 }
2472
2473 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002474 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002475 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 if (r != null) {
2477 final boolean resumed = !r.paused;
2478 if (!r.activity.mFinished && r.activity.mDecor != null
2479 && r.hideForNow && resumed) {
2480 // We had hidden the activity because it started another
2481 // one... we have gotten a result back and we are not
2482 // paused, so make sure our window is visible.
2483 updateVisibility(r, true);
2484 }
2485 if (resumed) {
2486 try {
2487 // Now we are idle.
2488 r.activity.mCalled = false;
2489 mInstrumentation.callActivityOnPause(r.activity);
2490 if (!r.activity.mCalled) {
2491 throw new SuperNotCalledException(
2492 "Activity " + r.intent.getComponent().toShortString()
2493 + " did not call through to super.onPause()");
2494 }
2495 } catch (SuperNotCalledException e) {
2496 throw e;
2497 } catch (Exception e) {
2498 if (!mInstrumentation.onException(r.activity, e)) {
2499 throw new RuntimeException(
2500 "Unable to pause activity "
2501 + r.intent.getComponent().toShortString()
2502 + ": " + e.toString(), e);
2503 }
2504 }
2505 }
2506 deliverResults(r, res.results);
2507 if (resumed) {
2508 mInstrumentation.callActivityOnResume(r.activity);
2509 }
2510 }
2511 }
2512
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002513 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 return performDestroyActivity(token, finishing, 0, false);
2515 }
2516
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002517 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002519 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002520 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 if (r != null) {
2522 r.activity.mConfigChangeFlags |= configChanges;
2523 if (finishing) {
2524 r.activity.mFinished = true;
2525 }
2526 if (!r.paused) {
2527 try {
2528 r.activity.mCalled = false;
2529 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002530 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 r.activity.getComponentName().getClassName());
2532 if (!r.activity.mCalled) {
2533 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002534 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 + " did not call through to super.onPause()");
2536 }
2537 } catch (SuperNotCalledException e) {
2538 throw e;
2539 } catch (Exception e) {
2540 if (!mInstrumentation.onException(r.activity, e)) {
2541 throw new RuntimeException(
2542 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002543 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 + ": " + e.toString(), e);
2545 }
2546 }
2547 r.paused = true;
2548 }
2549 if (!r.stopped) {
2550 try {
2551 r.activity.performStop();
2552 } catch (SuperNotCalledException e) {
2553 throw e;
2554 } catch (Exception e) {
2555 if (!mInstrumentation.onException(r.activity, e)) {
2556 throw new RuntimeException(
2557 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002558 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 + ": " + e.toString(), e);
2560 }
2561 }
2562 r.stopped = true;
2563 }
2564 if (getNonConfigInstance) {
2565 try {
2566 r.lastNonConfigurationInstance
2567 = r.activity.onRetainNonConfigurationInstance();
2568 } catch (Exception e) {
2569 if (!mInstrumentation.onException(r.activity, e)) {
2570 throw new RuntimeException(
2571 "Unable to retain activity "
2572 + r.intent.getComponent().toShortString()
2573 + ": " + e.toString(), e);
2574 }
2575 }
2576 try {
2577 r.lastNonConfigurationChildInstances
2578 = r.activity.onRetainNonConfigurationChildInstances();
2579 } catch (Exception e) {
2580 if (!mInstrumentation.onException(r.activity, e)) {
2581 throw new RuntimeException(
2582 "Unable to retain child activities "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002583 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 + ": " + e.toString(), e);
2585 }
2586 }
Bob Leee5408332009-09-04 18:31:17 -07002587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589 try {
2590 r.activity.mCalled = false;
2591 r.activity.onDestroy();
2592 if (!r.activity.mCalled) {
2593 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002594 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 " did not call through to super.onDestroy()");
2596 }
2597 if (r.window != null) {
2598 r.window.closeAllPanels();
2599 }
2600 } catch (SuperNotCalledException e) {
2601 throw e;
2602 } catch (Exception e) {
2603 if (!mInstrumentation.onException(r.activity, e)) {
2604 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002605 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2606 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 }
2608 }
2609 }
2610 mActivities.remove(token);
2611
2612 return r;
2613 }
2614
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002615 private static String safeToComponentShortString(Intent intent) {
2616 ComponentName component = intent.getComponent();
2617 return component == null ? "[Unknown]" : component.toShortString();
2618 }
2619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 private final void handleDestroyActivity(IBinder token, boolean finishing,
2621 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002622 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 configChanges, getNonConfigInstance);
2624 if (r != null) {
2625 WindowManager wm = r.activity.getWindowManager();
2626 View v = r.activity.mDecor;
2627 if (v != null) {
2628 if (r.activity.mVisibleFromServer) {
2629 mNumVisibleActivities--;
2630 }
2631 IBinder wtoken = v.getWindowToken();
2632 if (r.activity.mWindowAdded) {
2633 wm.removeViewImmediate(v);
2634 }
2635 if (wtoken != null) {
2636 WindowManagerImpl.getDefault().closeAll(wtoken,
2637 r.activity.getClass().getName(), "Activity");
2638 }
2639 r.activity.mDecor = null;
2640 }
2641 WindowManagerImpl.getDefault().closeAll(token,
2642 r.activity.getClass().getName(), "Activity");
2643
2644 // Mocked out contexts won't be participating in the normal
2645 // process lifecycle, but if we're running with a proper
2646 // ApplicationContext we need to have it tear down things
2647 // cleanly.
2648 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002649 if (c instanceof ContextImpl) {
2650 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 r.activity.getClass().getName(), "Activity");
2652 }
2653 }
2654 if (finishing) {
2655 try {
2656 ActivityManagerNative.getDefault().activityDestroyed(token);
2657 } catch (RemoteException ex) {
2658 // If the system process has died, it's game over for everyone.
2659 }
2660 }
2661 }
2662
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002663 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 // If we are getting ready to gc after going to the background, well
2665 // we are back active so skip it.
2666 unscheduleGcIdler();
2667
2668 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002669
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002670 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002671 + tmp.token + " with configChanges=0x"
2672 + Integer.toHexString(configChanges));
2673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 // First: make sure we have the most recent configuration and most
2675 // recent version of the activity, or skip it if some previous call
2676 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002677 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 int N = mRelaunchingActivities.size();
2679 IBinder token = tmp.token;
2680 tmp = null;
2681 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002682 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 if (r.token == token) {
2684 tmp = r;
2685 mRelaunchingActivities.remove(i);
2686 i--;
2687 N--;
2688 }
2689 }
Bob Leee5408332009-09-04 18:31:17 -07002690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002692 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 return;
2694 }
Bob Leee5408332009-09-04 18:31:17 -07002695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 if (mPendingConfiguration != null) {
2697 changedConfig = mPendingConfiguration;
2698 mPendingConfiguration = null;
2699 }
2700 }
Bob Leee5408332009-09-04 18:31:17 -07002701
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002702 if (tmp.createdConfig != null) {
2703 // If the activity manager is passing us its current config,
2704 // assume that is really what we want regardless of what we
2705 // may have pending.
2706 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002707 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2708 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2709 if (changedConfig == null
2710 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2711 changedConfig = tmp.createdConfig;
2712 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002713 }
2714 }
2715
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002716 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002717 + tmp.token + ": changedConfig=" + changedConfig);
2718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 // If there was a pending configuration change, execute it first.
2720 if (changedConfig != null) {
2721 handleConfigurationChanged(changedConfig);
2722 }
Bob Leee5408332009-09-04 18:31:17 -07002723
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002724 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002725 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 if (r == null) {
2727 return;
2728 }
Bob Leee5408332009-09-04 18:31:17 -07002729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002731 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 Bundle savedState = null;
2734 if (!r.paused) {
2735 savedState = performPauseActivity(r.token, false, true);
2736 }
Bob Leee5408332009-09-04 18:31:17 -07002737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 r.activity = null;
2741 r.window = null;
2742 r.hideForNow = false;
2743 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002744 // Merge any pending results and pending intents; don't just replace them
2745 if (tmp.pendingResults != null) {
2746 if (r.pendingResults == null) {
2747 r.pendingResults = tmp.pendingResults;
2748 } else {
2749 r.pendingResults.addAll(tmp.pendingResults);
2750 }
2751 }
2752 if (tmp.pendingIntents != null) {
2753 if (r.pendingIntents == null) {
2754 r.pendingIntents = tmp.pendingIntents;
2755 } else {
2756 r.pendingIntents.addAll(tmp.pendingIntents);
2757 }
2758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 r.startsNotResumed = tmp.startsNotResumed;
2760 if (savedState != null) {
2761 r.state = savedState;
2762 }
Bob Leee5408332009-09-04 18:31:17 -07002763
Christopher Tateb70f3df2009-04-07 16:07:59 -07002764 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 }
2766
2767 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002768 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 Bitmap thumbnail = createThumbnailBitmap(r);
2770 CharSequence description = null;
2771 try {
2772 description = r.activity.onCreateDescription();
2773 } catch (Exception e) {
2774 if (!mInstrumentation.onException(r.activity, e)) {
2775 throw new RuntimeException(
2776 "Unable to create description of activity "
2777 + r.intent.getComponent().toShortString()
2778 + ": " + e.toString(), e);
2779 }
2780 }
2781 //System.out.println("Reporting top thumbnail " + thumbnail);
2782 try {
2783 ActivityManagerNative.getDefault().reportThumbnail(
2784 token, thumbnail, description);
2785 } catch (RemoteException ex) {
2786 }
2787 }
2788
2789 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2790 boolean allActivities, Configuration newConfig) {
2791 ArrayList<ComponentCallbacks> callbacks
2792 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002795 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002797 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 Activity a = ar.activity;
2799 if (a != null) {
2800 if (!ar.activity.mFinished && (allActivities ||
2801 (a != null && !ar.paused))) {
2802 // If the activity is currently resumed, its configuration
2803 // needs to change right now.
2804 callbacks.add(a);
2805 } else if (newConfig != null) {
2806 // Otherwise, we will tell it about the change
2807 // the next time it is resumed or shown. Note that
2808 // the activity manager may, before then, decide the
2809 // activity needs to be destroyed to handle its new
2810 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002811 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002812 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 ar.newConfig = newConfig;
2814 }
2815 }
2816 }
2817 }
2818 if (mServices.size() > 0) {
2819 Iterator<Service> it = mServices.values().iterator();
2820 while (it.hasNext()) {
2821 callbacks.add(it.next());
2822 }
2823 }
2824 synchronized (mProviderMap) {
2825 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002826 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 while (it.hasNext()) {
2828 callbacks.add(it.next().mLocalProvider);
2829 }
2830 }
2831 }
2832 final int N = mAllApplications.size();
2833 for (int i=0; i<N; i++) {
2834 callbacks.add(mAllApplications.get(i));
2835 }
Bob Leee5408332009-09-04 18:31:17 -07002836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 return callbacks;
2838 }
Bob Leee5408332009-09-04 18:31:17 -07002839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 private final void performConfigurationChanged(
2841 ComponentCallbacks cb, Configuration config) {
2842 // Only for Activity objects, check that they actually call up to their
2843 // superclass implementation. ComponentCallbacks is an interface, so
2844 // we check the runtime type and act accordingly.
2845 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2846 if (activity != null) {
2847 activity.mCalled = false;
2848 }
Bob Leee5408332009-09-04 18:31:17 -07002849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 boolean shouldChangeConfig = false;
2851 if ((activity == null) || (activity.mCurrentConfig == null)) {
2852 shouldChangeConfig = true;
2853 } else {
Bob Leee5408332009-09-04 18:31:17 -07002854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 // If the new config is the same as the config this Activity
2856 // is already running with then don't bother calling
2857 // onConfigurationChanged
2858 int diff = activity.mCurrentConfig.diff(config);
2859 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 // If this activity doesn't handle any of the config changes
2862 // then don't bother calling onConfigurationChanged as we're
2863 // going to destroy it.
2864 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2865 shouldChangeConfig = true;
2866 }
2867 }
2868 }
Bob Leee5408332009-09-04 18:31:17 -07002869
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002870 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002871 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 if (shouldChangeConfig) {
2873 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 if (activity != null) {
2876 if (!activity.mCalled) {
2877 throw new SuperNotCalledException(
2878 "Activity " + activity.getLocalClassName() +
2879 " did not call through to super.onConfigurationChanged()");
2880 }
2881 activity.mConfigChangeFlags = 0;
2882 activity.mCurrentConfig = new Configuration(config);
2883 }
2884 }
2885 }
2886
Dianne Hackbornae078162010-03-18 11:29:37 -07002887 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002888 if (mResConfiguration == null) {
2889 mResConfiguration = new Configuration();
2890 }
2891 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002892 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002893 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002894 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002895 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002896 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002897 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002898
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002899 // set it for java, this also affects newly created Resources
2900 if (config.locale != null) {
2901 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
Bob Leee5408332009-09-04 18:31:17 -07002903
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002904 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07002905
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002906 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002907 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002908
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002909 Iterator<WeakReference<Resources>> it =
2910 mActiveResources.values().iterator();
2911 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
2912 // mActiveResources.entrySet().iterator();
2913 while (it.hasNext()) {
2914 WeakReference<Resources> v = it.next();
2915 Resources r = v.get();
2916 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002917 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002918 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002919 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002920 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002921 // + " " + r + ": " + r.getConfiguration());
2922 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002923 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002924 it.remove();
2925 }
2926 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002927
2928 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002929 }
2930
2931 final void handleConfigurationChanged(Configuration config) {
2932
2933 ArrayList<ComponentCallbacks> callbacks = null;
2934
2935 synchronized (mPackages) {
2936 if (mPendingConfiguration != null) {
2937 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
2938 config = mPendingConfiguration;
2939 }
2940 mPendingConfiguration = null;
2941 }
2942
2943 if (config == null) {
2944 return;
2945 }
2946
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002947 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002948 + config);
2949
2950 applyConfigurationToResourcesLocked(config);
2951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 if (mConfiguration == null) {
2953 mConfiguration = new Configuration();
2954 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002955 if (!mConfiguration.isOtherSeqNewer(config)) {
2956 return;
2957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07002959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 callbacks = collectComponentCallbacksLocked(false, config);
2961 }
Bob Leee5408332009-09-04 18:31:17 -07002962
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002963 if (callbacks != null) {
2964 final int N = callbacks.size();
2965 for (int i=0; i<N; i++) {
2966 performConfigurationChanged(callbacks.get(i), config);
2967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 }
2969 }
2970
2971 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002972 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 if (r == null || r.activity == null) {
2974 return;
2975 }
Bob Leee5408332009-09-04 18:31:17 -07002976
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002977 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002978 + r.activityInfo.name);
2979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 performConfigurationChanged(r.activity, mConfiguration);
2981 }
2982
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07002983 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08002984 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08002985 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07002986 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
2987 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08002988 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002989 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08002990 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07002991 } finally {
2992 try {
2993 pcd.fd.close();
2994 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002995 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07002996 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08002997 }
2998 } else {
2999 Debug.stopMethodTracing();
3000 }
3001 }
Bob Leee5408332009-09-04 18:31:17 -07003002
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003003 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3004 boolean hasPkgInfo = false;
3005 if (packages != null) {
3006 for (int i=packages.length-1; i>=0; i--) {
3007 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3008 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003009 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003010 ref = mPackages.get(packages[i]);
3011 if (ref != null && ref.get() != null) {
3012 hasPkgInfo = true;
3013 } else {
3014 ref = mResourcePackages.get(packages[i]);
3015 if (ref != null && ref.get() != null) {
3016 hasPkgInfo = true;
3017 }
3018 }
3019 }
3020 mPackages.remove(packages[i]);
3021 mResourcePackages.remove(packages[i]);
3022 }
3023 }
3024 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3025 hasPkgInfo);
3026 }
3027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 final void handleLowMemory() {
3029 ArrayList<ComponentCallbacks> callbacks
3030 = new ArrayList<ComponentCallbacks>();
3031
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003032 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 callbacks = collectComponentCallbacksLocked(true, null);
3034 }
Bob Leee5408332009-09-04 18:31:17 -07003035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 final int N = callbacks.size();
3037 for (int i=0; i<N; i++) {
3038 callbacks.get(i).onLowMemory();
3039 }
3040
Chris Tatece229052009-03-25 16:44:52 -07003041 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3042 if (Process.myUid() != Process.SYSTEM_UID) {
3043 int sqliteReleased = SQLiteDatabase.releaseMemory();
3044 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3045 }
Bob Leee5408332009-09-04 18:31:17 -07003046
Mike Reedcaf0df12009-04-27 14:32:05 -04003047 // Ask graphics to free up as much as possible (font/image caches)
3048 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049
3050 BinderInternal.forceGc("mem");
3051 }
3052
3053 private final void handleBindApplication(AppBindData data) {
3054 mBoundApplication = data;
3055 mConfiguration = new Configuration(data.config);
3056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003058 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 android.ddm.DdmHandleAppName.setAppName(data.processName);
3060
3061 /*
3062 * Before spawning a new process, reset the time zone to be the system time zone.
3063 * This needs to be done because the system time zone could have changed after the
3064 * the spawning of this process. Without doing this this process would have the incorrect
3065 * system time zone.
3066 */
3067 TimeZone.setDefault(null);
3068
3069 /*
3070 * Initialize the default locale in this process for the reasons we set the time zone.
3071 */
3072 Locale.setDefault(data.config.locale);
3073
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003074 /*
3075 * Update the system configuration since its preloaded and might not
3076 * reflect configuration changes. The configuration object passed
3077 * in AppBindData can be safely assumed to be up to date
3078 */
3079 Resources.getSystem().updateConfiguration(mConfiguration, null);
3080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 data.info = getPackageInfoNoCheck(data.appInfo);
3082
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003083 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003084 * For system applications on userdebug/eng builds, log stack
3085 * traces of disk and network access to dropbox for analysis.
3086 */
3087 if ((data.appInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0 &&
3088 !"user".equals(Build.TYPE)) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003089 StrictMode.setThreadBlockingPolicy(
3090 StrictMode.DISALLOW_DISK_WRITE |
3091 StrictMode.DISALLOW_DISK_READ |
3092 StrictMode.DISALLOW_NETWORK |
3093 StrictMode.PENALTY_DROPBOX);
3094 }
3095
3096 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003097 * Switch this process to density compatibility mode if needed.
3098 */
3099 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3100 == 0) {
3101 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3102 }
Bob Leee5408332009-09-04 18:31:17 -07003103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3105 // XXX should have option to change the port.
3106 Debug.changeDebugPort(8100);
3107 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003108 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 + " is waiting for the debugger on port 8100...");
3110
3111 IActivityManager mgr = ActivityManagerNative.getDefault();
3112 try {
3113 mgr.showWaitingForDebugger(mAppThread, true);
3114 } catch (RemoteException ex) {
3115 }
3116
3117 Debug.waitForDebugger();
3118
3119 try {
3120 mgr.showWaitingForDebugger(mAppThread, false);
3121 } catch (RemoteException ex) {
3122 }
3123
3124 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003125 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 + " can be debugged on port 8100...");
3127 }
3128 }
3129
3130 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003131 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 appContext.init(data.info, null, this);
3133 InstrumentationInfo ii = null;
3134 try {
3135 ii = appContext.getPackageManager().
3136 getInstrumentationInfo(data.instrumentationName, 0);
3137 } catch (PackageManager.NameNotFoundException e) {
3138 }
3139 if (ii == null) {
3140 throw new RuntimeException(
3141 "Unable to find instrumentation info for: "
3142 + data.instrumentationName);
3143 }
3144
3145 mInstrumentationAppDir = ii.sourceDir;
3146 mInstrumentationAppPackage = ii.packageName;
3147 mInstrumentedAppDir = data.info.getAppDir();
3148
3149 ApplicationInfo instrApp = new ApplicationInfo();
3150 instrApp.packageName = ii.packageName;
3151 instrApp.sourceDir = ii.sourceDir;
3152 instrApp.publicSourceDir = ii.publicSourceDir;
3153 instrApp.dataDir = ii.dataDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003154 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003156 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 instrContext.init(pi, null, this);
3158
3159 try {
3160 java.lang.ClassLoader cl = instrContext.getClassLoader();
3161 mInstrumentation = (Instrumentation)
3162 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3163 } catch (Exception e) {
3164 throw new RuntimeException(
3165 "Unable to instantiate instrumentation "
3166 + data.instrumentationName + ": " + e.toString(), e);
3167 }
3168
3169 mInstrumentation.init(this, instrContext, appContext,
3170 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3171
3172 if (data.profileFile != null && !ii.handleProfiling) {
3173 data.handlingProfiling = true;
3174 File file = new File(data.profileFile);
3175 file.getParentFile().mkdirs();
3176 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3177 }
3178
3179 try {
3180 mInstrumentation.onCreate(data.instrumentationArgs);
3181 }
3182 catch (Exception e) {
3183 throw new RuntimeException(
3184 "Exception thrown in onCreate() of "
3185 + data.instrumentationName + ": " + e.toString(), e);
3186 }
3187
3188 } else {
3189 mInstrumentation = new Instrumentation();
3190 }
3191
Christopher Tate181fafa2009-05-14 11:12:14 -07003192 // If the app is being launched for full backup or restore, bring it up in
3193 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003194 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 mInitialApplication = app;
3196
3197 List<ProviderInfo> providers = data.providers;
3198 if (providers != null) {
3199 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003200 // For process that contain content providers, we want to
3201 // ensure that the JIT is enabled "at some point".
3202 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 }
3204
3205 try {
3206 mInstrumentation.callApplicationOnCreate(app);
3207 } catch (Exception e) {
3208 if (!mInstrumentation.onException(app, e)) {
3209 throw new RuntimeException(
3210 "Unable to create application " + app.getClass().getName()
3211 + ": " + e.toString(), e);
3212 }
3213 }
3214 }
3215
3216 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3217 IActivityManager am = ActivityManagerNative.getDefault();
3218 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3219 Debug.stopMethodTracing();
3220 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003221 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 // + ", app thr: " + mAppThread);
3223 try {
3224 am.finishInstrumentation(mAppThread, resultCode, results);
3225 } catch (RemoteException ex) {
3226 }
3227 }
3228
3229 private final void installContentProviders(
3230 Context context, List<ProviderInfo> providers) {
3231 final ArrayList<IActivityManager.ContentProviderHolder> results =
3232 new ArrayList<IActivityManager.ContentProviderHolder>();
3233
3234 Iterator<ProviderInfo> i = providers.iterator();
3235 while (i.hasNext()) {
3236 ProviderInfo cpi = i.next();
3237 StringBuilder buf = new StringBuilder(128);
3238 buf.append("Publishing provider ");
3239 buf.append(cpi.authority);
3240 buf.append(": ");
3241 buf.append(cpi.name);
3242 Log.i(TAG, buf.toString());
3243 IContentProvider cp = installProvider(context, null, cpi, false);
3244 if (cp != null) {
3245 IActivityManager.ContentProviderHolder cph =
3246 new IActivityManager.ContentProviderHolder(cpi);
3247 cph.provider = cp;
3248 results.add(cph);
3249 // Don't ever unload this provider from the process.
3250 synchronized(mProviderMap) {
3251 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3252 }
3253 }
3254 }
3255
3256 try {
3257 ActivityManagerNative.getDefault().publishContentProviders(
3258 getApplicationThread(), results);
3259 } catch (RemoteException ex) {
3260 }
3261 }
3262
3263 private final IContentProvider getProvider(Context context, String name) {
3264 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003265 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 if (pr != null) {
3267 return pr.mProvider;
3268 }
3269 }
3270
3271 IActivityManager.ContentProviderHolder holder = null;
3272 try {
3273 holder = ActivityManagerNative.getDefault().getContentProvider(
3274 getApplicationThread(), name);
3275 } catch (RemoteException ex) {
3276 }
3277 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003278 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 return null;
3280 }
3281 if (holder.permissionFailure != null) {
3282 throw new SecurityException("Permission " + holder.permissionFailure
3283 + " required for provider " + name);
3284 }
3285
3286 IContentProvider prov = installProvider(context, holder.provider,
3287 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003288 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 if (holder.noReleaseNeeded || holder.provider == null) {
3290 // We are not going to release the provider if it is an external
3291 // provider that doesn't care about being released, or if it is
3292 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003293 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 synchronized(mProviderMap) {
3295 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3296 }
3297 }
3298 return prov;
3299 }
3300
3301 public final IContentProvider acquireProvider(Context c, String name) {
3302 IContentProvider provider = getProvider(c, name);
3303 if(provider == null)
3304 return null;
3305 IBinder jBinder = provider.asBinder();
3306 synchronized(mProviderMap) {
3307 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3308 if(prc == null) {
3309 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3310 } else {
3311 prc.count++;
3312 } //end else
3313 } //end synchronized
3314 return provider;
3315 }
3316
3317 public final boolean releaseProvider(IContentProvider provider) {
3318 if(provider == null) {
3319 return false;
3320 }
3321 IBinder jBinder = provider.asBinder();
3322 synchronized(mProviderMap) {
3323 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3324 if(prc == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003325 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldnt be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 return false;
3327 } else {
3328 prc.count--;
3329 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003330 // Schedule the actual remove asynchronously, since we
3331 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003332 // TODO: it would be nice to post a delayed message, so
3333 // if we come back and need the same provider quickly
3334 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003335 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3336 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 } //end if
3338 } //end else
3339 } //end synchronized
3340 return true;
3341 }
3342
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003343 final void completeRemoveProvider(IContentProvider provider) {
3344 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003345 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003346 synchronized(mProviderMap) {
3347 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3348 if(prc != null && prc.count == 0) {
3349 mProviderRefCountMap.remove(jBinder);
3350 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003351 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003352 }
3353 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003354
3355 if (name != null) {
3356 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003357 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003358 "ActivityManagerNative.removeContentProvider(" + name);
3359 ActivityManagerNative.getDefault().removeContentProvider(
3360 getApplicationThread(), name);
3361 } catch (RemoteException e) {
3362 //do nothing content provider object is dead any way
3363 } //end catch
3364 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003365 }
3366
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003367 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003369 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 }
3371 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003373 String name = null;
3374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003376 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003378 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 IBinder myBinder = pr.mProvider.asBinder();
3380 if (myBinder == providerBinder) {
3381 //find if its published by this process itself
3382 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003383 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003384 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003386 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 "death recipient");
3388 //content provider is in another process
3389 myBinder.unlinkToDeath(pr, 0);
3390 iter.remove();
3391 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003392 if(name == null) {
3393 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 }
3395 } //end if myBinder
3396 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003397
3398 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 }
3400
3401 final void removeDeadProvider(String name, IContentProvider provider) {
3402 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003403 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003405 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003406 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003407 if (removed != null) {
3408 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 }
3411 }
3412 }
3413
3414 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003415 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003417 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003418 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003419 if (removed != null) {
3420 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 }
3423 }
3424
3425 private final IContentProvider installProvider(Context context,
3426 IContentProvider provider, ProviderInfo info, boolean noisy) {
3427 ContentProvider localProvider = null;
3428 if (provider == null) {
3429 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003430 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 + info.name);
3432 }
3433 Context c = null;
3434 ApplicationInfo ai = info.applicationInfo;
3435 if (context.getPackageName().equals(ai.packageName)) {
3436 c = context;
3437 } else if (mInitialApplication != null &&
3438 mInitialApplication.getPackageName().equals(ai.packageName)) {
3439 c = mInitialApplication;
3440 } else {
3441 try {
3442 c = context.createPackageContext(ai.packageName,
3443 Context.CONTEXT_INCLUDE_CODE);
3444 } catch (PackageManager.NameNotFoundException e) {
3445 }
3446 }
3447 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003448 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 ai.packageName +
3450 " while loading content provider " +
3451 info.name);
3452 return null;
3453 }
3454 try {
3455 final java.lang.ClassLoader cl = c.getClassLoader();
3456 localProvider = (ContentProvider)cl.
3457 loadClass(info.name).newInstance();
3458 provider = localProvider.getIContentProvider();
3459 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003460 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 info.name + " from sourceDir " +
3462 info.applicationInfo.sourceDir);
3463 return null;
3464 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003465 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 TAG, "Instantiating local provider " + info.name);
3467 // XXX Need to create the correct context for this provider.
3468 localProvider.attachInfo(c, info);
3469 } catch (java.lang.Exception e) {
3470 if (!mInstrumentation.onException(null, e)) {
3471 throw new RuntimeException(
3472 "Unable to get provider " + info.name
3473 + ": " + e.toString(), e);
3474 }
3475 return null;
3476 }
3477 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003478 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 + info.name);
3480 }
3481
3482 synchronized (mProviderMap) {
3483 // Cache the pointer for the remote provider.
3484 String names[] = PATTERN_SEMICOLON.split(info.authority);
3485 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003486 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 localProvider);
3488 try {
3489 provider.asBinder().linkToDeath(pr, 0);
3490 mProviderMap.put(names[i], pr);
3491 } catch (RemoteException e) {
3492 return null;
3493 }
3494 }
3495 if (localProvider != null) {
3496 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003497 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 }
3499 }
3500
3501 return provider;
3502 }
3503
3504 private final void attach(boolean system) {
3505 sThreadLocal.set(this);
3506 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003508 ViewRoot.addFirstDrawHandler(new Runnable() {
3509 public void run() {
3510 ensureJitEnabled();
3511 }
3512 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3514 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3515 IActivityManager mgr = ActivityManagerNative.getDefault();
3516 try {
3517 mgr.attachApplication(mAppThread);
3518 } catch (RemoteException ex) {
3519 }
3520 } else {
3521 // Don't set application object here -- if the system crashes,
3522 // we can't display an alert, we just want to die die die.
3523 android.ddm.DdmHandleAppName.setAppName("system_process");
3524 try {
3525 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003526 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 context.init(getSystemContext().mPackageInfo, null, this);
3528 Application app = Instrumentation.newApplication(Application.class, context);
3529 mAllApplications.add(app);
3530 mInitialApplication = app;
3531 app.onCreate();
3532 } catch (Exception e) {
3533 throw new RuntimeException(
3534 "Unable to instantiate Application():" + e.toString(), e);
3535 }
3536 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003537
3538 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3539 public void onConfigurationChanged(Configuration newConfig) {
3540 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003541 // We need to apply this change to the resources
3542 // immediately, because upon returning the view
3543 // hierarchy will be informed about it.
3544 if (applyConfigurationToResourcesLocked(newConfig)) {
3545 // This actually changed the resources! Tell
3546 // everyone about it.
3547 if (mPendingConfiguration == null ||
3548 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3549 mPendingConfiguration = newConfig;
3550
3551 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3552 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003553 }
3554 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003555 }
3556 public void onLowMemory() {
3557 }
3558 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 }
3560
3561 private final void detach()
3562 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 sThreadLocal.set(null);
3564 }
3565
3566 public static final ActivityThread systemMain() {
3567 ActivityThread thread = new ActivityThread();
3568 thread.attach(true);
3569 return thread;
3570 }
3571
3572 public final void installSystemProviders(List providers) {
3573 if (providers != null) {
3574 installContentProviders(mInitialApplication,
3575 (List<ProviderInfo>)providers);
3576 }
3577 }
3578
3579 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003580 SamplingProfilerIntegration.start();
3581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 Process.setArgV0("<pre-initialized>");
3583
3584 Looper.prepareMainLooper();
3585
3586 ActivityThread thread = new ActivityThread();
3587 thread.attach(false);
3588
3589 Looper.loop();
3590
3591 if (Process.supportsProcesses()) {
3592 throw new RuntimeException("Main thread loop unexpectedly exited");
3593 }
3594
3595 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003596 String name = (thread.mInitialApplication != null)
3597 ? thread.mInitialApplication.getPackageName()
3598 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003599 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 }
3601}