blob: 2abe822c1014633736a9b2c6e4da611220ef742a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
Christopher Tate45281862010-03-05 15:46:30 -080019import android.app.backup.BackupAgent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.BroadcastReceiver;
21import android.content.ComponentCallbacks;
22import android.content.ComponentName;
23import android.content.ContentProvider;
24import android.content.Context;
25import android.content.IContentProvider;
26import android.content.Intent;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070027import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.ActivityInfo;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.IPackageManager;
31import android.content.pm.InstrumentationInfo;
32import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070033import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.pm.ProviderInfo;
35import android.content.pm.ServiceInfo;
36import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070037import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080042import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.Bitmap;
44import android.graphics.Canvas;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070045import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Bundle;
47import android.os.Debug;
48import android.os.Handler;
49import android.os.IBinder;
50import android.os.Looper;
51import android.os.Message;
52import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070053import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Process;
55import android.os.RemoteException;
56import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070057import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.SystemClock;
59import android.util.AndroidRuntimeException;
60import android.util.Config;
61import android.util.DisplayMetrics;
62import android.util.EventLog;
63import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -070064import android.util.LogPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080065import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.view.Display;
Romain Guy52339202010-09-03 16:04:46 -070067import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.View;
69import android.view.ViewDebug;
70import android.view.ViewManager;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080071import android.view.ViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.view.Window;
73import android.view.WindowManager;
74import android.view.WindowManagerImpl;
75
76import com.android.internal.os.BinderInternal;
77import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070078import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
81
82import java.io.File;
83import java.io.FileDescriptor;
84import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070085import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import java.io.PrintWriter;
87import java.lang.ref.WeakReference;
88import java.util.ArrayList;
89import java.util.HashMap;
90import java.util.Iterator;
91import java.util.List;
92import java.util.Locale;
93import java.util.Map;
94import java.util.TimeZone;
95import java.util.regex.Pattern;
96
Bob Leee5408332009-09-04 18:31:17 -070097import dalvik.system.SamplingProfiler;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099final class SuperNotCalledException extends AndroidRuntimeException {
100 public SuperNotCalledException(String msg) {
101 super(msg);
102 }
103}
104
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700105final class RemoteServiceException extends AndroidRuntimeException {
106 public RemoteServiceException(String msg) {
107 super(msg);
108 }
109}
110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111/**
112 * This manages the execution of the main thread in an
113 * application process, scheduling and executing activities,
114 * broadcasts, and other operations on it as the activity
115 * manager requests.
116 *
117 * {@hide}
118 */
119public final class ActivityThread {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700120 static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700121 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700123 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700124 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700125 static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700126 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700127 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700128 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
130 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
131 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
132 private static final int LOG_ON_PAUSE_CALLED = 30021;
133 private static final int LOG_ON_RESUME_CALLED = 30022;
134
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700135 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700136
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700137 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700139 final ApplicationThread mAppThread = new ApplicationThread();
140 final Looper mLooper = Looper.myLooper();
141 final H mH = new H();
142 final HashMap<IBinder, ActivityClientRecord> mActivities
143 = new HashMap<IBinder, ActivityClientRecord>();
144 // List of new activities (via ActivityRecord.nextIdle) that should
145 // be reported when next we idle.
146 ActivityClientRecord mNewActivities = null;
147 // Number of activities that are currently visible on-screen.
148 int mNumVisibleActivities = 0;
149 final HashMap<IBinder, Service> mServices
150 = new HashMap<IBinder, Service>();
151 AppBindData mBoundApplication;
152 Configuration mConfiguration;
153 Configuration mResConfiguration;
154 Application mInitialApplication;
155 final ArrayList<Application> mAllApplications
156 = new ArrayList<Application>();
157 // set of instantiated backup agents, keyed by package name
158 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700159 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700160 Instrumentation mInstrumentation;
161 String mInstrumentationAppDir = null;
162 String mInstrumentationAppPackage = null;
163 String mInstrumentedAppDir = null;
164 boolean mSystemThread = false;
165 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700167 // These can be accessed by multiple threads; mPackages is the lock.
168 // XXX For now we keep around information about all packages we have
169 // seen, not removing entries from this map.
170 final HashMap<String, WeakReference<LoadedApk>> mPackages
171 = new HashMap<String, WeakReference<LoadedApk>>();
172 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
173 = new HashMap<String, WeakReference<LoadedApk>>();
174 Display mDisplay = null;
175 DisplayMetrics mDisplayMetrics = null;
176 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
177 = new HashMap<ResourcesKey, WeakReference<Resources> >();
178 final ArrayList<ActivityClientRecord> mRelaunchingActivities
179 = new ArrayList<ActivityClientRecord>();
180 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700182 // The lock of mProviderMap protects the following variables.
183 final HashMap<String, ProviderClientRecord> mProviderMap
184 = new HashMap<String, ProviderClientRecord>();
185 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
186 = new HashMap<IBinder, ProviderRefCount>();
187 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
188 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700190 final GcIdler mGcIdler = new GcIdler();
191 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700193 static Handler sMainThreadHandler; // set once in main()
194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700195 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700197 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 Intent intent;
199 Bundle state;
200 Activity activity;
201 Window window;
202 Activity parent;
203 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700204 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 boolean paused;
206 boolean stopped;
207 boolean hideForNow;
208 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700209 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700210 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
212 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700213 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
215 List<ResultInfo> pendingResults;
216 List<Intent> pendingIntents;
217
218 boolean startsNotResumed;
219 boolean isForward;
220
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700221 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 parent = null;
223 embeddedID = null;
224 paused = false;
225 stopped = false;
226 hideForNow = false;
227 nextIdle = null;
228 }
229
230 public String toString() {
231 ComponentName componentName = intent.getComponent();
232 return "ActivityRecord{"
233 + Integer.toHexString(System.identityHashCode(this))
234 + " token=" + token + " " + (componentName == null
235 ? "no component name" : componentName.toShortString())
236 + "}";
237 }
238 }
239
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700240 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 final String mName;
242 final IContentProvider mProvider;
243 final ContentProvider mLocalProvider;
244
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700245 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 ContentProvider localProvider) {
247 mName = name;
248 mProvider = provider;
249 mLocalProvider = localProvider;
250 }
251
252 public void binderDied() {
253 removeDeadProvider(mName, mProvider);
254 }
255 }
256
257 private static final class NewIntentData {
258 List<Intent> intents;
259 IBinder token;
260 public String toString() {
261 return "NewIntentData{intents=" + intents + " token=" + token + "}";
262 }
263 }
264
265 private static final class ReceiverData {
266 Intent intent;
267 ActivityInfo info;
268 int resultCode;
269 String resultData;
270 Bundle resultExtras;
271 boolean sync;
272 boolean resultAbort;
273 public String toString() {
274 return "ReceiverData{intent=" + intent + " packageName=" +
275 info.packageName + " resultCode=" + resultCode
276 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
277 }
278 }
279
Christopher Tate181fafa2009-05-14 11:12:14 -0700280 private static final class CreateBackupAgentData {
281 ApplicationInfo appInfo;
282 int backupMode;
283 public String toString() {
284 return "CreateBackupAgentData{appInfo=" + appInfo
285 + " backupAgent=" + appInfo.backupAgentName
286 + " mode=" + backupMode + "}";
287 }
288 }
Bob Leee5408332009-09-04 18:31:17 -0700289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 private static final class CreateServiceData {
291 IBinder token;
292 ServiceInfo info;
293 Intent intent;
294 public String toString() {
295 return "CreateServiceData{token=" + token + " className="
296 + info.name + " packageName=" + info.packageName
297 + " intent=" + intent + "}";
298 }
299 }
300
301 private static final class BindServiceData {
302 IBinder token;
303 Intent intent;
304 boolean rebind;
305 public String toString() {
306 return "BindServiceData{token=" + token + " intent=" + intent + "}";
307 }
308 }
309
310 private static final class ServiceArgsData {
311 IBinder token;
312 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700313 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 Intent args;
315 public String toString() {
316 return "ServiceArgsData{token=" + token + " startId=" + startId
317 + " args=" + args + "}";
318 }
319 }
320
321 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700322 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 String processName;
324 ApplicationInfo appInfo;
325 List<ProviderInfo> providers;
326 ComponentName instrumentationName;
327 String profileFile;
328 Bundle instrumentationArgs;
329 IInstrumentationWatcher instrumentationWatcher;
330 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700331 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 Configuration config;
333 boolean handlingProfiling;
334 public String toString() {
335 return "AppBindData{appInfo=" + appInfo + "}";
336 }
337 }
338
Dianne Hackborn625ac272010-09-17 18:29:22 -0700339 private static final class DumpComponentInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 FileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700341 IBinder token;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 String[] args;
343 boolean dumped;
344 }
345
346 private static final class ResultData {
347 IBinder token;
348 List<ResultInfo> results;
349 public String toString() {
350 return "ResultData{token=" + token + " results" + results + "}";
351 }
352 }
353
354 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800355 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 String what;
357 String who;
358 }
359
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700360 private static final class ProfilerControlData {
361 String path;
362 ParcelFileDescriptor fd;
363 }
364
Andy McFadden824c5102010-07-09 16:26:57 -0700365 private static final class DumpHeapData {
366 String path;
367 ParcelFileDescriptor fd;
368 }
369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 private final class ApplicationThread extends ApplicationThreadNative {
371 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
372 private static final String ONE_COUNT_COLUMN = "%17s %8d";
373 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700374 private static final String TWO_COUNT_COLUMNS_DB = "%20s %8d %20s %8d";
375 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 // Formatting for checkin service - update version if row format changes
378 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 public final void schedulePauseActivity(IBinder token, boolean finished,
381 boolean userLeaving, int configChanges) {
382 queueOrSendMessage(
383 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
384 token,
385 (userLeaving ? 1 : 0),
386 configChanges);
387 }
388
389 public final void scheduleStopActivity(IBinder token, boolean showWindow,
390 int configChanges) {
391 queueOrSendMessage(
392 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
393 token, 0, configChanges);
394 }
395
396 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
397 queueOrSendMessage(
398 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
399 token);
400 }
401
402 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
403 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
404 }
405
406 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
407 ResultData res = new ResultData();
408 res.token = token;
409 res.results = results;
410 queueOrSendMessage(H.SEND_RESULT, res);
411 }
412
413 // we use token to identify this activity without having to send the
414 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700415 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
417 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700418 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419
420 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700421 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 r.intent = intent;
423 r.activityInfo = info;
424 r.state = state;
425
426 r.pendingResults = pendingResults;
427 r.pendingIntents = pendingNewIntents;
428
429 r.startsNotResumed = notResumed;
430 r.isForward = isForward;
431
432 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
433 }
434
435 public final void scheduleRelaunchActivity(IBinder token,
436 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800437 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700438 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439
440 r.token = token;
441 r.pendingResults = pendingResults;
442 r.pendingIntents = pendingNewIntents;
443 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800444 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800446 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 mRelaunchingActivities.add(r);
448 }
Bob Leee5408332009-09-04 18:31:17 -0700449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
451 }
452
453 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
454 NewIntentData data = new NewIntentData();
455 data.intents = intents;
456 data.token = token;
457
458 queueOrSendMessage(H.NEW_INTENT, data);
459 }
460
461 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
462 int configChanges) {
463 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
464 configChanges);
465 }
466
467 public final void scheduleReceiver(Intent intent, ActivityInfo info,
468 int resultCode, String data, Bundle extras, boolean sync) {
469 ReceiverData r = new ReceiverData();
470
471 r.intent = intent;
472 r.info = info;
473 r.resultCode = resultCode;
474 r.resultData = data;
475 r.resultExtras = extras;
476 r.sync = sync;
477
478 queueOrSendMessage(H.RECEIVER, r);
479 }
480
Christopher Tate181fafa2009-05-14 11:12:14 -0700481 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
482 CreateBackupAgentData d = new CreateBackupAgentData();
483 d.appInfo = app;
484 d.backupMode = backupMode;
485
486 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
487 }
488
489 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
490 CreateBackupAgentData d = new CreateBackupAgentData();
491 d.appInfo = app;
492
493 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
494 }
495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 public final void scheduleCreateService(IBinder token,
497 ServiceInfo info) {
498 CreateServiceData s = new CreateServiceData();
499 s.token = token;
500 s.info = info;
501
502 queueOrSendMessage(H.CREATE_SERVICE, s);
503 }
504
505 public final void scheduleBindService(IBinder token, Intent intent,
506 boolean rebind) {
507 BindServiceData s = new BindServiceData();
508 s.token = token;
509 s.intent = intent;
510 s.rebind = rebind;
511
512 queueOrSendMessage(H.BIND_SERVICE, s);
513 }
514
515 public final void scheduleUnbindService(IBinder token, Intent intent) {
516 BindServiceData s = new BindServiceData();
517 s.token = token;
518 s.intent = intent;
519
520 queueOrSendMessage(H.UNBIND_SERVICE, s);
521 }
522
523 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700524 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 ServiceArgsData s = new ServiceArgsData();
526 s.token = token;
527 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700528 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 s.args = args;
530
531 queueOrSendMessage(H.SERVICE_ARGS, s);
532 }
533
534 public final void scheduleStopService(IBinder token) {
535 queueOrSendMessage(H.STOP_SERVICE, token);
536 }
537
538 public final void bindApplication(String processName,
539 ApplicationInfo appInfo, List<ProviderInfo> providers,
540 ComponentName instrumentationName, String profileFile,
541 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700542 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544
545 if (services != null) {
546 // Setup the service cache in the ServiceManager
547 ServiceManager.initServiceCache(services);
548 }
549
550 AppBindData data = new AppBindData();
551 data.processName = processName;
552 data.appInfo = appInfo;
553 data.providers = providers;
554 data.instrumentationName = instrumentationName;
555 data.profileFile = profileFile;
556 data.instrumentationArgs = instrumentationArgs;
557 data.instrumentationWatcher = instrumentationWatcher;
558 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700559 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 data.config = config;
561 queueOrSendMessage(H.BIND_APPLICATION, data);
562 }
563
564 public final void scheduleExit() {
565 queueOrSendMessage(H.EXIT_APPLICATION, null);
566 }
567
Christopher Tate5e1ab332009-09-01 20:32:49 -0700568 public final void scheduleSuicide() {
569 queueOrSendMessage(H.SUICIDE, null);
570 }
571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 public void requestThumbnail(IBinder token) {
573 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
574 }
575
576 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800577 synchronized (mPackages) {
578 if (mPendingConfiguration == null ||
579 mPendingConfiguration.isOtherSeqNewer(config)) {
580 mPendingConfiguration = config;
581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 }
583 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
584 }
585
586 public void updateTimeZone() {
587 TimeZone.setDefault(null);
588 }
589
590 public void processInBackground() {
591 mH.removeMessages(H.GC_WHEN_IDLE);
592 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
593 }
594
595 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700596 DumpComponentInfo data = new DumpComponentInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 data.fd = fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700598 data.token = servicetoken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 data.args = args;
600 data.dumped = false;
601 queueOrSendMessage(H.DUMP_SERVICE, data);
602 synchronized (data) {
603 while (!data.dumped) {
604 try {
605 data.wait();
606 } catch (InterruptedException e) {
607 // no need to do anything here, we will keep waiting until
608 // dumped is set
609 }
610 }
611 }
612 }
613
614 // This function exists to make sure all receiver dispatching is
615 // correctly ordered, since these are one-way calls and the binder driver
616 // applies transaction ordering per object for such calls.
617 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700618 int resultCode, String dataStr, Bundle extras, boolean ordered,
619 boolean sticky) throws RemoteException {
620 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 }
Bob Leee5408332009-09-04 18:31:17 -0700622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 public void scheduleLowMemory() {
624 queueOrSendMessage(H.LOW_MEMORY, null);
625 }
626
627 public void scheduleActivityConfigurationChanged(IBinder token) {
628 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
629 }
630
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700631 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
632 ProfilerControlData pcd = new ProfilerControlData();
633 pcd.path = path;
634 pcd.fd = fd;
635 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800636 }
637
Andy McFadden824c5102010-07-09 16:26:57 -0700638 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
639 DumpHeapData dhd = new DumpHeapData();
640 dhd.path = path;
641 dhd.fd = fd;
642 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
643 }
644
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700645 public void setSchedulingGroup(int group) {
646 // Note: do this immediately, since going into the foreground
647 // should happen regardless of what pending work we have to do
648 // and the activity manager will wait for us to report back that
649 // we are done before sending us to the background.
650 try {
651 Process.setProcessGroup(Process.myPid(), group);
652 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800653 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700654 }
655 }
Bob Leee5408332009-09-04 18:31:17 -0700656
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700657 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
658 Debug.getMemoryInfo(outInfo);
659 }
Bob Leee5408332009-09-04 18:31:17 -0700660
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700661 public void dispatchPackageBroadcast(int cmd, String[] packages) {
662 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
663 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700664
665 public void scheduleCrash(String msg) {
666 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
667 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700668
669 public void dumpActivity(FileDescriptor fd, IBinder activitytoken, String[] args) {
670 DumpComponentInfo data = new DumpComponentInfo();
671 data.fd = fd;
672 data.token = activitytoken;
673 data.args = args;
674 data.dumped = false;
675 queueOrSendMessage(H.DUMP_ACTIVITY, data);
676 synchronized (data) {
677 while (!data.dumped) {
678 try {
679 data.wait();
680 } catch (InterruptedException e) {
681 // no need to do anything here, we will keep waiting until
682 // dumped is set
683 }
684 }
685 }
686 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 @Override
689 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
690 long nativeMax = Debug.getNativeHeapSize() / 1024;
691 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
692 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
693
694 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
695 Debug.getMemoryInfo(memInfo);
696
697 final int nativeShared = memInfo.nativeSharedDirty;
698 final int dalvikShared = memInfo.dalvikSharedDirty;
699 final int otherShared = memInfo.otherSharedDirty;
700
701 final int nativePrivate = memInfo.nativePrivateDirty;
702 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
703 final int otherPrivate = memInfo.otherPrivateDirty;
704
705 Runtime runtime = Runtime.getRuntime();
706
707 long dalvikMax = runtime.totalMemory() / 1024;
708 long dalvikFree = runtime.freeMemory() / 1024;
709 long dalvikAllocated = dalvikMax - dalvikFree;
710 long viewInstanceCount = ViewDebug.getViewInstanceCount();
711 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700712 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
713 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 int globalAssetCount = AssetManager.getGlobalAssetCount();
715 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
716 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
717 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
718 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700719 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800721 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 // Check to see if we were called by checkin server. If so, print terse format.
724 boolean doCheckinFormat = false;
725 if (args != null) {
726 for (String arg : args) {
727 if ("-c".equals(arg)) doCheckinFormat = true;
728 }
729 }
Bob Leee5408332009-09-04 18:31:17 -0700730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 // For checkin, we print one long comma-separated list of values
732 if (doCheckinFormat) {
733 // NOTE: if you change anything significant below, also consider changing
734 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700735 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 // Header
739 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
740 pw.print(Process.myPid()); pw.print(',');
741 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 // Heap info - max
744 pw.print(nativeMax); pw.print(',');
745 pw.print(dalvikMax); pw.print(',');
746 pw.print("N/A,");
747 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 // Heap info - allocated
750 pw.print(nativeAllocated); pw.print(',');
751 pw.print(dalvikAllocated); pw.print(',');
752 pw.print("N/A,");
753 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 // Heap info - free
756 pw.print(nativeFree); pw.print(',');
757 pw.print(dalvikFree); pw.print(',');
758 pw.print("N/A,");
759 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 // Heap info - proportional set size
762 pw.print(memInfo.nativePss); pw.print(',');
763 pw.print(memInfo.dalvikPss); pw.print(',');
764 pw.print(memInfo.otherPss); pw.print(',');
765 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700768 pw.print(nativeShared); pw.print(',');
769 pw.print(dalvikShared); pw.print(',');
770 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700774 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 pw.print(dalvikPrivate); pw.print(',');
776 pw.print(otherPrivate); pw.print(',');
777 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 // Object counts
780 pw.print(viewInstanceCount); pw.print(',');
781 pw.print(viewRootInstanceCount); pw.print(',');
782 pw.print(appContextInstanceCount); pw.print(',');
783 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 pw.print(globalAssetCount); pw.print(',');
786 pw.print(globalAssetManagerCount); pw.print(',');
787 pw.print(binderLocalObjectCount); pw.print(',');
788 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 pw.print(binderDeathObjectCount); pw.print(',');
791 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 // SQL
794 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800795 pw.print(stats.memoryUsed / 1024); pw.print(',');
796 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
797 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
798 for (int i = 0; i < stats.dbStats.size(); i++) {
799 DbStats dbStats = stats.dbStats.get(i);
800 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700801 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800802 pw.print(',');
803 }
Bob Leee5408332009-09-04 18:31:17 -0700804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 return;
806 }
Bob Leee5408332009-09-04 18:31:17 -0700807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 // otherwise, show human-readable format
809 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
810 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
811 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
812 nativeAllocated + dalvikAllocated);
813 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
814 nativeFree + dalvikFree);
815
816 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
817 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
818
819 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
820 nativeShared + dalvikShared + otherShared);
821 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
822 nativePrivate + dalvikPrivate + otherPrivate);
823
824 pw.println(" ");
825 pw.println(" Objects");
826 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
827 viewRootInstanceCount);
828
829 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
830 "Activities:", activityInstanceCount);
831
832 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
833 "AssetManagers:", globalAssetManagerCount);
834
835 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
836 "Proxy Binders:", binderProxyObjectCount);
837 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
838
839 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 // SQLite mem info
842 pw.println(" ");
843 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700844 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800845 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700846 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
847 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800848 pw.println(" ");
849 int N = stats.dbStats.size();
850 if (N > 0) {
851 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700852 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
853 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800854 for (int i = 0; i < N; i++) {
855 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700856 printRow(pw, DB_INFO_FORMAT,
857 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
858 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
859 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
860 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800861 }
862 }
Bob Leee5408332009-09-04 18:31:17 -0700863
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700864 // Asset details.
865 String assetAlloc = AssetManager.getAssetAllocations();
866 if (assetAlloc != null) {
867 pw.println(" ");
868 pw.println(" Asset Allocations");
869 pw.print(assetAlloc);
870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 }
872
873 private void printRow(PrintWriter pw, String format, Object...objs) {
874 pw.println(String.format(format, objs));
875 }
876 }
877
878 private final class H extends Handler {
879 public static final int LAUNCH_ACTIVITY = 100;
880 public static final int PAUSE_ACTIVITY = 101;
881 public static final int PAUSE_ACTIVITY_FINISHING= 102;
882 public static final int STOP_ACTIVITY_SHOW = 103;
883 public static final int STOP_ACTIVITY_HIDE = 104;
884 public static final int SHOW_WINDOW = 105;
885 public static final int HIDE_WINDOW = 106;
886 public static final int RESUME_ACTIVITY = 107;
887 public static final int SEND_RESULT = 108;
888 public static final int DESTROY_ACTIVITY = 109;
889 public static final int BIND_APPLICATION = 110;
890 public static final int EXIT_APPLICATION = 111;
891 public static final int NEW_INTENT = 112;
892 public static final int RECEIVER = 113;
893 public static final int CREATE_SERVICE = 114;
894 public static final int SERVICE_ARGS = 115;
895 public static final int STOP_SERVICE = 116;
896 public static final int REQUEST_THUMBNAIL = 117;
897 public static final int CONFIGURATION_CHANGED = 118;
898 public static final int CLEAN_UP_CONTEXT = 119;
899 public static final int GC_WHEN_IDLE = 120;
900 public static final int BIND_SERVICE = 121;
901 public static final int UNBIND_SERVICE = 122;
902 public static final int DUMP_SERVICE = 123;
903 public static final int LOW_MEMORY = 124;
904 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
905 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800906 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700907 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700908 public static final int DESTROY_BACKUP_AGENT = 129;
909 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700910 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800911 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700912 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700913 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700914 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700915 public static final int DUMP_ACTIVITY = 136;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700917 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 switch (code) {
919 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
920 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
921 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
922 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
923 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
924 case SHOW_WINDOW: return "SHOW_WINDOW";
925 case HIDE_WINDOW: return "HIDE_WINDOW";
926 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
927 case SEND_RESULT: return "SEND_RESULT";
928 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
929 case BIND_APPLICATION: return "BIND_APPLICATION";
930 case EXIT_APPLICATION: return "EXIT_APPLICATION";
931 case NEW_INTENT: return "NEW_INTENT";
932 case RECEIVER: return "RECEIVER";
933 case CREATE_SERVICE: return "CREATE_SERVICE";
934 case SERVICE_ARGS: return "SERVICE_ARGS";
935 case STOP_SERVICE: return "STOP_SERVICE";
936 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
937 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
938 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
939 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
940 case BIND_SERVICE: return "BIND_SERVICE";
941 case UNBIND_SERVICE: return "UNBIND_SERVICE";
942 case DUMP_SERVICE: return "DUMP_SERVICE";
943 case LOW_MEMORY: return "LOW_MEMORY";
944 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
945 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800946 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700947 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
948 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700949 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700950 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800951 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700952 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700953 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -0700954 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -0700955 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 }
957 }
958 return "(unknown)";
959 }
960 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700961 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 switch (msg.what) {
963 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700964 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965
966 r.packageInfo = getPackageInfoNoCheck(
967 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700968 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 } break;
970 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700971 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 handleRelaunchActivity(r, msg.arg1);
973 } break;
974 case PAUSE_ACTIVITY:
975 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700976 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 break;
978 case PAUSE_ACTIVITY_FINISHING:
979 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
980 break;
981 case STOP_ACTIVITY_SHOW:
982 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
983 break;
984 case STOP_ACTIVITY_HIDE:
985 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
986 break;
987 case SHOW_WINDOW:
988 handleWindowVisibility((IBinder)msg.obj, true);
989 break;
990 case HIDE_WINDOW:
991 handleWindowVisibility((IBinder)msg.obj, false);
992 break;
993 case RESUME_ACTIVITY:
994 handleResumeActivity((IBinder)msg.obj, true,
995 msg.arg1 != 0);
996 break;
997 case SEND_RESULT:
998 handleSendResult((ResultData)msg.obj);
999 break;
1000 case DESTROY_ACTIVITY:
1001 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1002 msg.arg2, false);
1003 break;
1004 case BIND_APPLICATION:
1005 AppBindData data = (AppBindData)msg.obj;
1006 handleBindApplication(data);
1007 break;
1008 case EXIT_APPLICATION:
1009 if (mInitialApplication != null) {
1010 mInitialApplication.onTerminate();
1011 }
1012 Looper.myLooper().quit();
1013 break;
1014 case NEW_INTENT:
1015 handleNewIntent((NewIntentData)msg.obj);
1016 break;
1017 case RECEIVER:
1018 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001019 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 break;
1021 case CREATE_SERVICE:
1022 handleCreateService((CreateServiceData)msg.obj);
1023 break;
1024 case BIND_SERVICE:
1025 handleBindService((BindServiceData)msg.obj);
1026 break;
1027 case UNBIND_SERVICE:
1028 handleUnbindService((BindServiceData)msg.obj);
1029 break;
1030 case SERVICE_ARGS:
1031 handleServiceArgs((ServiceArgsData)msg.obj);
1032 break;
1033 case STOP_SERVICE:
1034 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001035 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 break;
1037 case REQUEST_THUMBNAIL:
1038 handleRequestThumbnail((IBinder)msg.obj);
1039 break;
1040 case CONFIGURATION_CHANGED:
1041 handleConfigurationChanged((Configuration)msg.obj);
1042 break;
1043 case CLEAN_UP_CONTEXT:
1044 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1045 cci.context.performFinalCleanup(cci.who, cci.what);
1046 break;
1047 case GC_WHEN_IDLE:
1048 scheduleGcIdler();
1049 break;
1050 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001051 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 break;
1053 case LOW_MEMORY:
1054 handleLowMemory();
1055 break;
1056 case ACTIVITY_CONFIGURATION_CHANGED:
1057 handleActivityConfigurationChanged((IBinder)msg.obj);
1058 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001059 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001060 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001061 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001062 case CREATE_BACKUP_AGENT:
1063 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1064 break;
1065 case DESTROY_BACKUP_AGENT:
1066 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1067 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001068 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001069 Process.killProcess(Process.myPid());
1070 break;
1071 case REMOVE_PROVIDER:
1072 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001073 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001074 case ENABLE_JIT:
1075 ensureJitEnabled();
1076 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001077 case DISPATCH_PACKAGE_BROADCAST:
1078 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1079 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001080 case SCHEDULE_CRASH:
1081 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001082 case DUMP_HEAP:
1083 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1084 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001085 case DUMP_ACTIVITY:
1086 handleDumpActivity((DumpComponentInfo)msg.obj);
1087 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001089 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 }
Bob Leee5408332009-09-04 18:31:17 -07001091
1092 void maybeSnapshot() {
1093 if (mBoundApplication != null) {
Sen Hubde75702010-05-28 01:54:03 -07001094 // convert the *private* ActivityThread.PackageInfo to *public* known
1095 // android.content.pm.PackageInfo
1096 String packageName = mBoundApplication.info.mPackageName;
1097 android.content.pm.PackageInfo packageInfo = null;
1098 try {
1099 Context context = getSystemContext();
1100 if(context == null) {
1101 Log.e(TAG, "cannot get a valid context");
1102 return;
1103 }
1104 PackageManager pm = context.getPackageManager();
1105 if(pm == null) {
1106 Log.e(TAG, "cannot get a valid PackageManager");
1107 return;
1108 }
1109 packageInfo = pm.getPackageInfo(
1110 packageName, PackageManager.GET_ACTIVITIES);
1111 } catch (NameNotFoundException e) {
1112 Log.e(TAG, "cannot get package info for " + packageName, e);
1113 }
1114 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001115 }
1116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
1118
1119 private final class Idler implements MessageQueue.IdleHandler {
1120 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001121 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 if (a != null) {
1123 mNewActivities = null;
1124 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001125 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001127 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 TAG, "Reporting idle of " + a +
1129 " finished=" +
1130 (a.activity != null ? a.activity.mFinished : false));
1131 if (a.activity != null && !a.activity.mFinished) {
1132 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001133 am.activityIdle(a.token, a.createdConfig);
1134 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 } catch (RemoteException ex) {
1136 }
1137 }
1138 prev = a;
1139 a = a.nextIdle;
1140 prev.nextIdle = null;
1141 } while (a != null);
1142 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001143 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 return false;
1145 }
1146 }
1147
1148 final class GcIdler implements MessageQueue.IdleHandler {
1149 public final boolean queueIdle() {
1150 doGcIfNeeded();
1151 return false;
1152 }
1153 }
1154
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001155 private final static class ResourcesKey {
1156 final private String mResDir;
1157 final private float mScale;
1158 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001159
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001160 ResourcesKey(String resDir, float scale) {
1161 mResDir = resDir;
1162 mScale = scale;
1163 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1164 }
Bob Leee5408332009-09-04 18:31:17 -07001165
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001166 @Override
1167 public int hashCode() {
1168 return mHash;
1169 }
1170
1171 @Override
1172 public boolean equals(Object obj) {
1173 if (!(obj instanceof ResourcesKey)) {
1174 return false;
1175 }
1176 ResourcesKey peer = (ResourcesKey) obj;
1177 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1178 }
1179 }
1180
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001181 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001182 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001185 public static final String currentPackageName() {
1186 ActivityThread am = currentActivityThread();
1187 return (am != null && am.mBoundApplication != null)
1188 ? am.mBoundApplication.processName : null;
1189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001191 public static final Application currentApplication() {
1192 ActivityThread am = currentActivityThread();
1193 return am != null ? am.mInitialApplication : null;
1194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001196 public static IPackageManager getPackageManager() {
1197 if (sPackageManager != null) {
1198 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1199 return sPackageManager;
1200 }
1201 IBinder b = ServiceManager.getService("package");
1202 //Slog.v("PackageManager", "default service binder = " + b);
1203 sPackageManager = IPackageManager.Stub.asInterface(b);
1204 //Slog.v("PackageManager", "default service = " + sPackageManager);
1205 return sPackageManager;
1206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001208 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1209 if (mDisplayMetrics != null && !forceUpdate) {
1210 return mDisplayMetrics;
1211 }
1212 if (mDisplay == null) {
1213 WindowManager wm = WindowManagerImpl.getDefault();
1214 mDisplay = wm.getDefaultDisplay();
1215 }
1216 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1217 mDisplay.getMetrics(metrics);
1218 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1219 // + metrics.heightPixels + " den=" + metrics.density
1220 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1221 return metrics;
1222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001224 /**
1225 * Creates the top level Resources for applications with the given compatibility info.
1226 *
1227 * @param resDir the resource directory.
1228 * @param compInfo the compability info. It will use the default compatibility info when it's
1229 * null.
1230 */
1231 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1232 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1233 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001235 // Resources is app scale dependent.
1236 if (false) {
1237 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1238 + compInfo.applicationScale);
1239 }
1240 WeakReference<Resources> wr = mActiveResources.get(key);
1241 r = wr != null ? wr.get() : null;
1242 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1243 if (r != null && r.getAssets().isUpToDate()) {
1244 if (false) {
1245 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1246 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1247 }
1248 return r;
1249 }
1250 }
1251
1252 //if (r != null) {
1253 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1254 // + r + " " + resDir);
1255 //}
1256
1257 AssetManager assets = new AssetManager();
1258 if (assets.addAssetPath(resDir) == 0) {
1259 return null;
1260 }
1261
1262 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1263 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1264 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1265 if (false) {
1266 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1267 + r.getConfiguration() + " appScale="
1268 + r.getCompatibilityInfo().applicationScale);
1269 }
1270
1271 synchronized (mPackages) {
1272 WeakReference<Resources> wr = mActiveResources.get(key);
1273 Resources existing = wr != null ? wr.get() : null;
1274 if (existing != null && existing.getAssets().isUpToDate()) {
1275 // Someone else already created the resources while we were
1276 // unlocked; go ahead and use theirs.
1277 r.getAssets().close();
1278 return existing;
1279 }
1280
1281 // XXX need to remove entries when weak references go away
1282 mActiveResources.put(key, new WeakReference<Resources>(r));
1283 return r;
1284 }
1285 }
1286
1287 /**
1288 * Creates the top level resources for the given package.
1289 */
1290 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1291 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1292 }
1293
1294 final Handler getHandler() {
1295 return mH;
1296 }
1297
1298 public final LoadedApk getPackageInfo(String packageName, int flags) {
1299 synchronized (mPackages) {
1300 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1302 ref = mPackages.get(packageName);
1303 } else {
1304 ref = mResourcePackages.get(packageName);
1305 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001306 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001307 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001308 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1309 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 if (packageInfo != null && (packageInfo.mResources == null
1311 || packageInfo.mResources.getAssets().isUpToDate())) {
1312 if (packageInfo.isSecurityViolation()
1313 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1314 throw new SecurityException(
1315 "Requesting code from " + packageName
1316 + " to be run in process "
1317 + mBoundApplication.processName
1318 + "/" + mBoundApplication.appInfo.uid);
1319 }
1320 return packageInfo;
1321 }
1322 }
1323
1324 ApplicationInfo ai = null;
1325 try {
1326 ai = getPackageManager().getApplicationInfo(packageName,
1327 PackageManager.GET_SHARED_LIBRARY_FILES);
1328 } catch (RemoteException e) {
1329 }
1330
1331 if (ai != null) {
1332 return getPackageInfo(ai, flags);
1333 }
1334
1335 return null;
1336 }
1337
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001338 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1340 boolean securityViolation = includeCode && ai.uid != 0
1341 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1342 ? ai.uid != mBoundApplication.appInfo.uid : true);
1343 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1344 |Context.CONTEXT_IGNORE_SECURITY))
1345 == Context.CONTEXT_INCLUDE_CODE) {
1346 if (securityViolation) {
1347 String msg = "Requesting code from " + ai.packageName
1348 + " (with uid " + ai.uid + ")";
1349 if (mBoundApplication != null) {
1350 msg = msg + " to be run in process "
1351 + mBoundApplication.processName + " (with uid "
1352 + mBoundApplication.appInfo.uid + ")";
1353 }
1354 throw new SecurityException(msg);
1355 }
1356 }
1357 return getPackageInfo(ai, null, securityViolation, includeCode);
1358 }
1359
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001360 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 return getPackageInfo(ai, null, false, true);
1362 }
1363
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001364 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1366 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001367 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 if (includeCode) {
1369 ref = mPackages.get(aInfo.packageName);
1370 } else {
1371 ref = mResourcePackages.get(aInfo.packageName);
1372 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001373 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 if (packageInfo == null || (packageInfo.mResources != null
1375 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001376 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 : "Loading resource-only package ") + aInfo.packageName
1378 + " (in " + (mBoundApplication != null
1379 ? mBoundApplication.processName : null)
1380 + ")");
1381 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001382 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 securityViolation, includeCode &&
1384 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1385 if (includeCode) {
1386 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001387 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 } else {
1389 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001390 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
1392 }
1393 return packageInfo;
1394 }
1395 }
1396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 ActivityThread() {
1398 }
1399
1400 public ApplicationThread getApplicationThread()
1401 {
1402 return mAppThread;
1403 }
1404
1405 public Instrumentation getInstrumentation()
1406 {
1407 return mInstrumentation;
1408 }
1409
1410 public Configuration getConfiguration() {
1411 return mConfiguration;
1412 }
1413
1414 public boolean isProfiling() {
1415 return mBoundApplication != null && mBoundApplication.profileFile != null;
1416 }
1417
1418 public String getProfileFilePath() {
1419 return mBoundApplication.profileFile;
1420 }
1421
1422 public Looper getLooper() {
1423 return mLooper;
1424 }
1425
1426 public Application getApplication() {
1427 return mInitialApplication;
1428 }
Bob Leee5408332009-09-04 18:31:17 -07001429
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001430 public String getProcessName() {
1431 return mBoundApplication.processName;
1432 }
Bob Leee5408332009-09-04 18:31:17 -07001433
Dianne Hackborn21556372010-02-04 16:34:40 -08001434 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 synchronized (this) {
1436 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001437 ContextImpl context =
1438 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001439 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 context.init(info, null, this);
1441 context.getResources().updateConfiguration(
1442 getConfiguration(), getDisplayMetricsLocked(false));
1443 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001444 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 // + ": " + context.getResources().getConfiguration());
1446 }
1447 }
1448 return mSystemContext;
1449 }
1450
Mike Cleron432b7132009-09-24 15:28:29 -07001451 public void installSystemApplicationInfo(ApplicationInfo info) {
1452 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001453 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001454 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001455 }
1456 }
1457
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001458 void ensureJitEnabled() {
1459 if (!mJitEnabled) {
1460 mJitEnabled = true;
1461 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1462 }
1463 }
1464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 void scheduleGcIdler() {
1466 if (!mGcIdlerScheduled) {
1467 mGcIdlerScheduled = true;
1468 Looper.myQueue().addIdleHandler(mGcIdler);
1469 }
1470 mH.removeMessages(H.GC_WHEN_IDLE);
1471 }
1472
1473 void unscheduleGcIdler() {
1474 if (mGcIdlerScheduled) {
1475 mGcIdlerScheduled = false;
1476 Looper.myQueue().removeIdleHandler(mGcIdler);
1477 }
1478 mH.removeMessages(H.GC_WHEN_IDLE);
1479 }
1480
1481 void doGcIfNeeded() {
1482 mGcIdlerScheduled = false;
1483 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001484 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 // + "m now=" + now);
1486 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001487 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 BinderInternal.forceGc("bg");
1489 }
1490 }
1491
1492 public final ActivityInfo resolveActivityInfo(Intent intent) {
1493 ActivityInfo aInfo = intent.resolveActivityInfo(
1494 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1495 if (aInfo == null) {
1496 // Throw an exception.
1497 Instrumentation.checkStartActivityResult(
1498 IActivityManager.START_CLASS_NOT_FOUND, intent);
1499 }
1500 return aInfo;
1501 }
Bob Leee5408332009-09-04 18:31:17 -07001502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001505 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001506 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001508 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 r.intent = intent;
1510 r.state = state;
1511 r.parent = parent;
1512 r.embeddedID = id;
1513 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001514 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 if (localLOGV) {
1516 ComponentName compname = intent.getComponent();
1517 String name;
1518 if (compname != null) {
1519 name = compname.toShortString();
1520 } else {
1521 name = "(Intent " + intent + ").getComponent() returned null";
1522 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001523 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 + ", comp=" + name
1525 + ", token=" + token);
1526 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001527 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
1529
1530 public final Activity getActivity(IBinder token) {
1531 return mActivities.get(token).activity;
1532 }
1533
1534 public final void sendActivityResult(
1535 IBinder token, String id, int requestCode,
1536 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001537 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001538 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1540 list.add(new ResultInfo(id, requestCode, resultCode, data));
1541 mAppThread.scheduleSendResult(token, list);
1542 }
1543
1544 // if the thread hasn't started yet, we don't have the handler, so just
1545 // save the messages until we're ready.
1546 private final void queueOrSendMessage(int what, Object obj) {
1547 queueOrSendMessage(what, obj, 0, 0);
1548 }
1549
1550 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1551 queueOrSendMessage(what, obj, arg1, 0);
1552 }
1553
1554 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1555 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001556 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1558 + ": " + arg1 + " / " + obj);
1559 Message msg = Message.obtain();
1560 msg.what = what;
1561 msg.obj = obj;
1562 msg.arg1 = arg1;
1563 msg.arg2 = arg2;
1564 mH.sendMessage(msg);
1565 }
1566 }
1567
Dianne Hackborn21556372010-02-04 16:34:40 -08001568 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 String what) {
1570 ContextCleanupInfo cci = new ContextCleanupInfo();
1571 cci.context = context;
1572 cci.who = who;
1573 cci.what = what;
1574 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1575 }
1576
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001577 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1579
1580 ActivityInfo aInfo = r.activityInfo;
1581 if (r.packageInfo == null) {
1582 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1583 Context.CONTEXT_INCLUDE_CODE);
1584 }
Bob Leee5408332009-09-04 18:31:17 -07001585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 ComponentName component = r.intent.getComponent();
1587 if (component == null) {
1588 component = r.intent.resolveActivity(
1589 mInitialApplication.getPackageManager());
1590 r.intent.setComponent(component);
1591 }
1592
1593 if (r.activityInfo.targetActivity != null) {
1594 component = new ComponentName(r.activityInfo.packageName,
1595 r.activityInfo.targetActivity);
1596 }
1597
1598 Activity activity = null;
1599 try {
1600 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1601 activity = mInstrumentation.newActivity(
1602 cl, component.getClassName(), r.intent);
1603 r.intent.setExtrasClassLoader(cl);
1604 if (r.state != null) {
1605 r.state.setClassLoader(cl);
1606 }
1607 } catch (Exception e) {
1608 if (!mInstrumentation.onException(activity, e)) {
1609 throw new RuntimeException(
1610 "Unable to instantiate activity " + component
1611 + ": " + e.toString(), e);
1612 }
1613 }
1614
1615 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001616 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001617
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001618 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1619 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 TAG, r + ": app=" + app
1621 + ", appName=" + app.getPackageName()
1622 + ", pkg=" + r.packageInfo.getPackageName()
1623 + ", comp=" + r.intent.getComponent().toShortString()
1624 + ", dir=" + r.packageInfo.getAppDir());
1625
1626 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001627 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 appContext.init(r.packageInfo, r.token, this);
1629 appContext.setOuterContext(activity);
1630 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1631 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001632 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001633 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001634 activity.attach(appContext, this, getInstrumentation(), r.token,
1635 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001636 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001637
Christopher Tateb70f3df2009-04-07 16:07:59 -07001638 if (customIntent != null) {
1639 activity.mIntent = customIntent;
1640 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001641 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 activity.mStartedActivity = false;
1643 int theme = r.activityInfo.getThemeResource();
1644 if (theme != 0) {
1645 activity.setTheme(theme);
1646 }
1647
1648 activity.mCalled = false;
1649 mInstrumentation.callActivityOnCreate(activity, r.state);
1650 if (!activity.mCalled) {
1651 throw new SuperNotCalledException(
1652 "Activity " + r.intent.getComponent().toShortString() +
1653 " did not call through to super.onCreate()");
1654 }
1655 r.activity = activity;
1656 r.stopped = true;
1657 if (!r.activity.mFinished) {
1658 activity.performStart();
1659 r.stopped = false;
1660 }
1661 if (!r.activity.mFinished) {
1662 if (r.state != null) {
1663 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1664 }
1665 }
1666 if (!r.activity.mFinished) {
1667 activity.mCalled = false;
1668 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1669 if (!activity.mCalled) {
1670 throw new SuperNotCalledException(
1671 "Activity " + r.intent.getComponent().toShortString() +
1672 " did not call through to super.onPostCreate()");
1673 }
1674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 }
1676 r.paused = true;
1677
1678 mActivities.put(r.token, r);
1679
1680 } catch (SuperNotCalledException e) {
1681 throw e;
1682
1683 } catch (Exception e) {
1684 if (!mInstrumentation.onException(activity, e)) {
1685 throw new RuntimeException(
1686 "Unable to start activity " + component
1687 + ": " + e.toString(), e);
1688 }
1689 }
1690
1691 return activity;
1692 }
1693
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001694 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 // If we are getting ready to gc after going to the background, well
1696 // we are back active so skip it.
1697 unscheduleGcIdler();
1698
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001699 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001701 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702
1703 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001704 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001705 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 handleResumeActivity(r.token, false, r.isForward);
1707
1708 if (!r.activity.mFinished && r.startsNotResumed) {
1709 // The activity manager actually wants this one to start out
1710 // paused, because it needs to be visible but isn't in the
1711 // foreground. We accomplish this by going through the
1712 // normal startup (because activities expect to go through
1713 // onResume() the first time they run, before their window
1714 // is displayed), and then pausing it. However, in this case
1715 // we do -not- need to do the full pause cycle (of freezing
1716 // and such) because the activity manager assumes it can just
1717 // retain the current state it has.
1718 try {
1719 r.activity.mCalled = false;
1720 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001721 // We need to keep around the original state, in case
1722 // we need to be created again.
1723 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 if (!r.activity.mCalled) {
1725 throw new SuperNotCalledException(
1726 "Activity " + r.intent.getComponent().toShortString() +
1727 " did not call through to super.onPause()");
1728 }
1729
1730 } catch (SuperNotCalledException e) {
1731 throw e;
1732
1733 } catch (Exception e) {
1734 if (!mInstrumentation.onException(r.activity, e)) {
1735 throw new RuntimeException(
1736 "Unable to pause activity "
1737 + r.intent.getComponent().toShortString()
1738 + ": " + e.toString(), e);
1739 }
1740 }
1741 r.paused = true;
1742 }
1743 } else {
1744 // If there was an error, for any reason, tell the activity
1745 // manager to stop us.
1746 try {
1747 ActivityManagerNative.getDefault()
1748 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1749 } catch (RemoteException ex) {
1750 }
1751 }
1752 }
1753
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001754 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 List<Intent> intents) {
1756 final int N = intents.size();
1757 for (int i=0; i<N; i++) {
1758 Intent intent = intents.get(i);
1759 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001760 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1762 }
1763 }
1764
1765 public final void performNewIntents(IBinder token,
1766 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001767 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 if (r != null) {
1769 final boolean resumed = !r.paused;
1770 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001771 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 mInstrumentation.callActivityOnPause(r.activity);
1773 }
1774 deliverNewIntents(r, intents);
1775 if (resumed) {
1776 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001777 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
1779 }
1780 }
Bob Leee5408332009-09-04 18:31:17 -07001781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 private final void handleNewIntent(NewIntentData data) {
1783 performNewIntents(data.token, data.intents);
1784 }
1785
1786 private final void handleReceiver(ReceiverData data) {
1787 // If we are getting ready to gc after going to the background, well
1788 // we are back active so skip it.
1789 unscheduleGcIdler();
1790
1791 String component = data.intent.getComponent().getClassName();
1792
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001793 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 data.info.applicationInfo);
1795
1796 IActivityManager mgr = ActivityManagerNative.getDefault();
1797
1798 BroadcastReceiver receiver = null;
1799 try {
1800 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1801 data.intent.setExtrasClassLoader(cl);
1802 if (data.resultExtras != null) {
1803 data.resultExtras.setClassLoader(cl);
1804 }
1805 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1806 } catch (Exception e) {
1807 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001808 if (DEBUG_BROADCAST) Slog.i(TAG,
1809 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1811 data.resultData, data.resultExtras, data.resultAbort);
1812 } catch (RemoteException ex) {
1813 }
1814 throw new RuntimeException(
1815 "Unable to instantiate receiver " + component
1816 + ": " + e.toString(), e);
1817 }
1818
1819 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001820 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001821
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001822 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 TAG, "Performing receive of " + data.intent
1824 + ": app=" + app
1825 + ", appName=" + app.getPackageName()
1826 + ", pkg=" + packageInfo.getPackageName()
1827 + ", comp=" + data.intent.getComponent().toShortString()
1828 + ", dir=" + packageInfo.getAppDir());
1829
Dianne Hackborn21556372010-02-04 16:34:40 -08001830 ContextImpl context = (ContextImpl)app.getBaseContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 receiver.setOrderedHint(true);
1832 receiver.setResult(data.resultCode, data.resultData,
1833 data.resultExtras);
1834 receiver.setOrderedHint(data.sync);
1835 receiver.onReceive(context.getReceiverRestrictedContext(),
1836 data.intent);
1837 } catch (Exception e) {
1838 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001839 if (DEBUG_BROADCAST) Slog.i(TAG,
1840 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1842 data.resultData, data.resultExtras, data.resultAbort);
1843 } catch (RemoteException ex) {
1844 }
1845 if (!mInstrumentation.onException(receiver, e)) {
1846 throw new RuntimeException(
1847 "Unable to start receiver " + component
1848 + ": " + e.toString(), e);
1849 }
1850 }
1851
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001852 QueuedWork.waitToFinish();
1853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 try {
1855 if (data.sync) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001856 if (DEBUG_BROADCAST) Slog.i(TAG,
1857 "Finishing ordered broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 mgr.finishReceiver(
1859 mAppThread.asBinder(), receiver.getResultCode(),
1860 receiver.getResultData(), receiver.getResultExtras(false),
1861 receiver.getAbortBroadcast());
1862 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001863 if (DEBUG_BROADCAST) Slog.i(TAG,
1864 "Finishing broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
1866 }
1867 } catch (RemoteException ex) {
1868 }
1869 }
1870
Christopher Tate181fafa2009-05-14 11:12:14 -07001871 // Instantiate a BackupAgent and tell it that it's alive
1872 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001873 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001874
1875 // no longer idle; we have backup work to do
1876 unscheduleGcIdler();
1877
1878 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001879 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001880 String packageName = packageInfo.mPackageName;
1881 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001882 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001883 + " already exists");
1884 return;
1885 }
Bob Leee5408332009-09-04 18:31:17 -07001886
Christopher Tate181fafa2009-05-14 11:12:14 -07001887 BackupAgent agent = null;
1888 String classname = data.appInfo.backupAgentName;
1889 if (classname == null) {
1890 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001891 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001892 + packageName);
1893 return;
1894 }
1895 classname = "android.app.FullBackupAgent";
1896 }
1897 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001898 IBinder binder = null;
1899 try {
1900 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1901 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1902
1903 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001904 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001905 + data.appInfo.backupAgentName);
1906
Dianne Hackborn21556372010-02-04 16:34:40 -08001907 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001908 context.init(packageInfo, null, this);
1909 context.setOuterContext(agent);
1910 agent.attach(context);
1911
1912 agent.onCreate();
1913 binder = agent.onBind();
1914 mBackupAgents.put(packageName, agent);
1915 } catch (Exception e) {
1916 // If this is during restore, fail silently; otherwise go
1917 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001918 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001919 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1920 throw e;
1921 }
1922 // falling through with 'binder' still null
1923 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001924
1925 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001926 try {
1927 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1928 } catch (RemoteException e) {
1929 // nothing to do.
1930 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001931 } catch (Exception e) {
1932 throw new RuntimeException("Unable to create BackupAgent "
1933 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1934 }
1935 }
1936
1937 // Tear down a BackupAgent
1938 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001939 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001940
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001941 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001942 String packageName = packageInfo.mPackageName;
1943 BackupAgent agent = mBackupAgents.get(packageName);
1944 if (agent != null) {
1945 try {
1946 agent.onDestroy();
1947 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001948 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001949 e.printStackTrace();
1950 }
1951 mBackupAgents.remove(packageName);
1952 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001953 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001954 }
1955 }
1956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 private final void handleCreateService(CreateServiceData data) {
1958 // If we are getting ready to gc after going to the background, well
1959 // we are back active so skip it.
1960 unscheduleGcIdler();
1961
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001962 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 data.info.applicationInfo);
1964 Service service = null;
1965 try {
1966 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1967 service = (Service) cl.loadClass(data.info.name).newInstance();
1968 } catch (Exception e) {
1969 if (!mInstrumentation.onException(service, e)) {
1970 throw new RuntimeException(
1971 "Unable to instantiate service " + data.info.name
1972 + ": " + e.toString(), e);
1973 }
1974 }
1975
1976 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001977 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978
Dianne Hackborn21556372010-02-04 16:34:40 -08001979 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 context.init(packageInfo, null, this);
1981
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001982 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 context.setOuterContext(service);
1984 service.attach(context, this, data.info.name, data.token, app,
1985 ActivityManagerNative.getDefault());
1986 service.onCreate();
1987 mServices.put(data.token, service);
1988 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001989 ActivityManagerNative.getDefault().serviceDoneExecuting(
1990 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 } catch (RemoteException e) {
1992 // nothing to do.
1993 }
1994 } catch (Exception e) {
1995 if (!mInstrumentation.onException(service, e)) {
1996 throw new RuntimeException(
1997 "Unable to create service " + data.info.name
1998 + ": " + e.toString(), e);
1999 }
2000 }
2001 }
2002
2003 private final void handleBindService(BindServiceData data) {
2004 Service s = mServices.get(data.token);
2005 if (s != null) {
2006 try {
2007 data.intent.setExtrasClassLoader(s.getClassLoader());
2008 try {
2009 if (!data.rebind) {
2010 IBinder binder = s.onBind(data.intent);
2011 ActivityManagerNative.getDefault().publishService(
2012 data.token, data.intent, binder);
2013 } else {
2014 s.onRebind(data.intent);
2015 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002016 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002018 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 } catch (RemoteException ex) {
2020 }
2021 } catch (Exception e) {
2022 if (!mInstrumentation.onException(s, e)) {
2023 throw new RuntimeException(
2024 "Unable to bind to service " + s
2025 + " with " + data.intent + ": " + e.toString(), e);
2026 }
2027 }
2028 }
2029 }
2030
2031 private final void handleUnbindService(BindServiceData data) {
2032 Service s = mServices.get(data.token);
2033 if (s != null) {
2034 try {
2035 data.intent.setExtrasClassLoader(s.getClassLoader());
2036 boolean doRebind = s.onUnbind(data.intent);
2037 try {
2038 if (doRebind) {
2039 ActivityManagerNative.getDefault().unbindFinished(
2040 data.token, data.intent, doRebind);
2041 } else {
2042 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002043 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045 } catch (RemoteException ex) {
2046 }
2047 } catch (Exception e) {
2048 if (!mInstrumentation.onException(s, e)) {
2049 throw new RuntimeException(
2050 "Unable to unbind to service " + s
2051 + " with " + data.intent + ": " + e.toString(), e);
2052 }
2053 }
2054 }
2055 }
2056
Dianne Hackborn625ac272010-09-17 18:29:22 -07002057 private void handleDumpService(DumpComponentInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002059 Service s = mServices.get(info.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 if (s != null) {
2061 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2062 s.dump(info.fd, pw, info.args);
2063 pw.close();
2064 }
2065 } finally {
2066 synchronized (info) {
2067 info.dumped = true;
2068 info.notifyAll();
2069 }
2070 }
2071 }
2072
Dianne Hackborn625ac272010-09-17 18:29:22 -07002073 private void handleDumpActivity(DumpComponentInfo info) {
2074 try {
2075 ActivityClientRecord r = mActivities.get(info.token);
2076 if (r != null && r.activity != null) {
2077 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2078 r.activity.dump(info.fd, pw, info.args);
2079 pw.close();
2080 }
2081 } finally {
2082 synchronized (info) {
2083 info.dumped = true;
2084 info.notifyAll();
2085 }
2086 }
2087 }
2088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 private final void handleServiceArgs(ServiceArgsData data) {
2090 Service s = mServices.get(data.token);
2091 if (s != null) {
2092 try {
2093 if (data.args != null) {
2094 data.args.setExtrasClassLoader(s.getClassLoader());
2095 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002096 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002097
2098 QueuedWork.waitToFinish();
2099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002101 ActivityManagerNative.getDefault().serviceDoneExecuting(
2102 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 } catch (RemoteException e) {
2104 // nothing to do.
2105 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002106 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 } catch (Exception e) {
2108 if (!mInstrumentation.onException(s, e)) {
2109 throw new RuntimeException(
2110 "Unable to start service " + s
2111 + " with " + data.args + ": " + e.toString(), e);
2112 }
2113 }
2114 }
2115 }
2116
2117 private final void handleStopService(IBinder token) {
2118 Service s = mServices.remove(token);
2119 if (s != null) {
2120 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002121 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 s.onDestroy();
2123 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002124 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002126 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002128
2129 QueuedWork.waitToFinish();
2130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002132 ActivityManagerNative.getDefault().serviceDoneExecuting(
2133 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 } catch (RemoteException e) {
2135 // nothing to do.
2136 }
2137 } catch (Exception e) {
2138 if (!mInstrumentation.onException(s, e)) {
2139 throw new RuntimeException(
2140 "Unable to stop service " + s
2141 + ": " + e.toString(), e);
2142 }
2143 }
2144 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002145 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 }
2147
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002148 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002150 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002151 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 + " finished=" + r.activity.mFinished);
2153 if (r != null && !r.activity.mFinished) {
2154 if (clearHide) {
2155 r.hideForNow = false;
2156 r.activity.mStartedActivity = false;
2157 }
2158 try {
2159 if (r.pendingIntents != null) {
2160 deliverNewIntents(r, r.pendingIntents);
2161 r.pendingIntents = null;
2162 }
2163 if (r.pendingResults != null) {
2164 deliverResults(r, r.pendingResults);
2165 r.pendingResults = null;
2166 }
2167 r.activity.performResume();
2168
Bob Leee5408332009-09-04 18:31:17 -07002169 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 r.paused = false;
2173 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 r.state = null;
2175 } catch (Exception e) {
2176 if (!mInstrumentation.onException(r.activity, e)) {
2177 throw new RuntimeException(
2178 "Unable to resume activity "
2179 + r.intent.getComponent().toShortString()
2180 + ": " + e.toString(), e);
2181 }
2182 }
2183 }
2184 return r;
2185 }
2186
2187 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2188 // If we are getting ready to gc after going to the background, well
2189 // we are back active so skip it.
2190 unscheduleGcIdler();
2191
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002192 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193
2194 if (r != null) {
2195 final Activity a = r.activity;
2196
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002197 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 TAG, "Resume " + r + " started activity: " +
2199 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2200 + ", finished: " + a.mFinished);
2201
2202 final int forwardBit = isForward ?
2203 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 // If the window hasn't yet been added to the window manager,
2206 // and this guy didn't finish itself or start another activity,
2207 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002208 boolean willBeVisible = !a.mStartedActivity;
2209 if (!willBeVisible) {
2210 try {
2211 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2212 a.getActivityToken());
2213 } catch (RemoteException e) {
2214 }
2215 }
2216 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 r.window = r.activity.getWindow();
2218 View decor = r.window.getDecorView();
2219 decor.setVisibility(View.INVISIBLE);
2220 ViewManager wm = a.getWindowManager();
2221 WindowManager.LayoutParams l = r.window.getAttributes();
2222 a.mDecor = decor;
2223 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2224 l.softInputMode |= forwardBit;
2225 if (a.mVisibleFromClient) {
2226 a.mWindowAdded = true;
2227 wm.addView(decor, l);
2228 }
2229
2230 // If the window has already been added, but during resume
2231 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002232 // window visible.
2233 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002234 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 TAG, "Launch " + r + " mStartedActivity set");
2236 r.hideForNow = true;
2237 }
2238
2239 // The window is now visible if it has been added, we are not
2240 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002241 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002242 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002244 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002245 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 performConfigurationChanged(r.activity, r.newConfig);
2247 r.newConfig = null;
2248 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002249 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 + isForward);
2251 WindowManager.LayoutParams l = r.window.getAttributes();
2252 if ((l.softInputMode
2253 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2254 != forwardBit) {
2255 l.softInputMode = (l.softInputMode
2256 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2257 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002258 if (r.activity.mVisibleFromClient) {
2259 ViewManager wm = a.getWindowManager();
2260 View decor = r.window.getDecorView();
2261 wm.updateViewLayout(decor, l);
2262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 }
2264 r.activity.mVisibleFromServer = true;
2265 mNumVisibleActivities++;
2266 if (r.activity.mVisibleFromClient) {
2267 r.activity.makeVisible();
2268 }
2269 }
2270
2271 r.nextIdle = mNewActivities;
2272 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002273 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 TAG, "Scheduling idle handler for " + r);
2275 Looper.myQueue().addIdleHandler(new Idler());
2276
2277 } else {
2278 // If an exception was thrown when trying to resume, then
2279 // just end this activity.
2280 try {
2281 ActivityManagerNative.getDefault()
2282 .finishActivity(token, Activity.RESULT_CANCELED, null);
2283 } catch (RemoteException ex) {
2284 }
2285 }
2286 }
2287
2288 private int mThumbnailWidth = -1;
2289 private int mThumbnailHeight = -1;
2290
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002291 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 Bitmap thumbnail = null;
2293 try {
2294 int w = mThumbnailWidth;
2295 int h;
2296 if (w < 0) {
2297 Resources res = r.activity.getResources();
2298 mThumbnailHeight = h =
2299 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2300
2301 mThumbnailWidth = w =
2302 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2303 } else {
2304 h = mThumbnailHeight;
2305 }
2306
Jim Miller0b2a6d02010-07-13 18:01:29 -07002307 // On platforms where we don't want thumbnails, set dims to (0,0)
2308 if ((w > 0) && (h > 0)) {
2309 View topView = r.activity.getWindow().getDecorView();
2310
2311 // Maximize bitmap by capturing in native aspect.
2312 if (topView.getWidth() >= topView.getHeight()) {
2313 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2314 } else {
2315 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2316 }
2317
2318 thumbnail.eraseColor(0);
2319 Canvas cv = new Canvas(thumbnail);
2320 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2321 thumbnail = null;
2322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 } catch (Exception e) {
2326 if (!mInstrumentation.onException(r.activity, e)) {
2327 throw new RuntimeException(
2328 "Unable to create thumbnail of "
2329 + r.intent.getComponent().toShortString()
2330 + ": " + e.toString(), e);
2331 }
2332 thumbnail = null;
2333 }
2334
2335 return thumbnail;
2336 }
2337
2338 private final void handlePauseActivity(IBinder token, boolean finished,
2339 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002340 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002342 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 if (userLeaving) {
2344 performUserLeavingActivity(r);
2345 }
Bob Leee5408332009-09-04 18:31:17 -07002346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 r.activity.mConfigChangeFlags |= configChanges;
2348 Bundle state = performPauseActivity(token, finished, true);
2349
2350 // Tell the activity manager we have paused.
2351 try {
2352 ActivityManagerNative.getDefault().activityPaused(token, state);
2353 } catch (RemoteException ex) {
2354 }
2355 }
2356 }
2357
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002358 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 mInstrumentation.callActivityOnUserLeaving(r.activity);
2360 }
2361
2362 final Bundle performPauseActivity(IBinder token, boolean finished,
2363 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002364 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 return r != null ? performPauseActivity(r, finished, saveState) : null;
2366 }
2367
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002368 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 boolean saveState) {
2370 if (r.paused) {
2371 if (r.activity.mFinished) {
2372 // If we are finishing, we won't call onResume() in certain cases.
2373 // So here we likewise don't want to call onPause() if the activity
2374 // isn't resumed.
2375 return null;
2376 }
2377 RuntimeException e = new RuntimeException(
2378 "Performing pause of activity that is not resumed: "
2379 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002380 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 }
2382 Bundle state = null;
2383 if (finished) {
2384 r.activity.mFinished = true;
2385 }
2386 try {
2387 // Next have the activity save its current state and managed dialogs...
2388 if (!r.activity.mFinished && saveState) {
2389 state = new Bundle();
2390 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2391 r.state = state;
2392 }
2393 // Now we are idle.
2394 r.activity.mCalled = false;
2395 mInstrumentation.callActivityOnPause(r.activity);
2396 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2397 if (!r.activity.mCalled) {
2398 throw new SuperNotCalledException(
2399 "Activity " + r.intent.getComponent().toShortString() +
2400 " did not call through to super.onPause()");
2401 }
2402
2403 } catch (SuperNotCalledException e) {
2404 throw e;
2405
2406 } catch (Exception e) {
2407 if (!mInstrumentation.onException(r.activity, e)) {
2408 throw new RuntimeException(
2409 "Unable to pause activity "
2410 + r.intent.getComponent().toShortString()
2411 + ": " + e.toString(), e);
2412 }
2413 }
2414 r.paused = true;
2415 return state;
2416 }
2417
2418 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002419 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 performStopActivityInner(r, null, false);
2421 }
2422
2423 private static class StopInfo {
2424 Bitmap thumbnail;
2425 CharSequence description;
2426 }
2427
2428 private final class ProviderRefCount {
2429 public int count;
2430 ProviderRefCount(int pCount) {
2431 count = pCount;
2432 }
2433 }
2434
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002435 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002437 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 if (r != null) {
2439 if (!keepShown && r.stopped) {
2440 if (r.activity.mFinished) {
2441 // If we are finishing, we won't call onResume() in certain
2442 // cases. So here we likewise don't want to call onStop()
2443 // if the activity isn't resumed.
2444 return;
2445 }
2446 RuntimeException e = new RuntimeException(
2447 "Performing stop of activity that is not resumed: "
2448 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002449 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
2451
2452 if (info != null) {
2453 try {
2454 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002455 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 info.description = r.activity.onCreateDescription();
2457 } catch (Exception e) {
2458 if (!mInstrumentation.onException(r.activity, e)) {
2459 throw new RuntimeException(
2460 "Unable to save state of activity "
2461 + r.intent.getComponent().toShortString()
2462 + ": " + e.toString(), e);
2463 }
2464 }
2465 }
2466
2467 if (!keepShown) {
2468 try {
2469 // Now we are idle.
2470 r.activity.performStop();
2471 } catch (Exception e) {
2472 if (!mInstrumentation.onException(r.activity, e)) {
2473 throw new RuntimeException(
2474 "Unable to stop activity "
2475 + r.intent.getComponent().toShortString()
2476 + ": " + e.toString(), e);
2477 }
2478 }
2479 r.stopped = true;
2480 }
2481
2482 r.paused = true;
2483 }
2484 }
2485
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002486 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 View v = r.activity.mDecor;
2488 if (v != null) {
2489 if (show) {
2490 if (!r.activity.mVisibleFromServer) {
2491 r.activity.mVisibleFromServer = true;
2492 mNumVisibleActivities++;
2493 if (r.activity.mVisibleFromClient) {
2494 r.activity.makeVisible();
2495 }
2496 }
2497 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002498 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002499 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 performConfigurationChanged(r.activity, r.newConfig);
2501 r.newConfig = null;
2502 }
2503 } else {
2504 if (r.activity.mVisibleFromServer) {
2505 r.activity.mVisibleFromServer = false;
2506 mNumVisibleActivities--;
2507 v.setVisibility(View.INVISIBLE);
2508 }
2509 }
2510 }
2511 }
2512
2513 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002514 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 r.activity.mConfigChangeFlags |= configChanges;
2516
2517 StopInfo info = new StopInfo();
2518 performStopActivityInner(r, info, show);
2519
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002520 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 TAG, "Finishing stop of " + r + ": show=" + show
2522 + " win=" + r.window);
2523
2524 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 // Tell activity manager we have been stopped.
2527 try {
2528 ActivityManagerNative.getDefault().activityStopped(
2529 r.token, info.thumbnail, info.description);
2530 } catch (RemoteException ex) {
2531 }
2532 }
2533
2534 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002535 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 if (r.stopped) {
2537 r.activity.performRestart();
2538 r.stopped = false;
2539 }
2540 }
2541
2542 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002543 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 if (!show && !r.stopped) {
2545 performStopActivityInner(r, null, show);
2546 } else if (show && r.stopped) {
2547 // If we are getting ready to gc after going to the background, well
2548 // we are back active so skip it.
2549 unscheduleGcIdler();
2550
2551 r.activity.performRestart();
2552 r.stopped = false;
2553 }
2554 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002555 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 TAG, "Handle window " + r + " visibility: " + show);
2557 updateVisibility(r, show);
2558 }
2559 }
2560
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002561 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 final int N = results.size();
2563 for (int i=0; i<N; i++) {
2564 ResultInfo ri = results.get(i);
2565 try {
2566 if (ri.mData != null) {
2567 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2568 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002569 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002570 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 r.activity.dispatchActivityResult(ri.mResultWho,
2572 ri.mRequestCode, ri.mResultCode, ri.mData);
2573 } catch (Exception e) {
2574 if (!mInstrumentation.onException(r.activity, e)) {
2575 throw new RuntimeException(
2576 "Failure delivering result " + ri + " to activity "
2577 + r.intent.getComponent().toShortString()
2578 + ": " + e.toString(), e);
2579 }
2580 }
2581 }
2582 }
2583
2584 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002585 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002586 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 if (r != null) {
2588 final boolean resumed = !r.paused;
2589 if (!r.activity.mFinished && r.activity.mDecor != null
2590 && r.hideForNow && resumed) {
2591 // We had hidden the activity because it started another
2592 // one... we have gotten a result back and we are not
2593 // paused, so make sure our window is visible.
2594 updateVisibility(r, true);
2595 }
2596 if (resumed) {
2597 try {
2598 // Now we are idle.
2599 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002600 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 mInstrumentation.callActivityOnPause(r.activity);
2602 if (!r.activity.mCalled) {
2603 throw new SuperNotCalledException(
2604 "Activity " + r.intent.getComponent().toShortString()
2605 + " did not call through to super.onPause()");
2606 }
2607 } catch (SuperNotCalledException e) {
2608 throw e;
2609 } catch (Exception e) {
2610 if (!mInstrumentation.onException(r.activity, e)) {
2611 throw new RuntimeException(
2612 "Unable to pause activity "
2613 + r.intent.getComponent().toShortString()
2614 + ": " + e.toString(), e);
2615 }
2616 }
2617 }
2618 deliverResults(r, res.results);
2619 if (resumed) {
2620 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002621 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 }
2623 }
2624 }
2625
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002626 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 return performDestroyActivity(token, finishing, 0, false);
2628 }
2629
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002630 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002632 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002633 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 if (r != null) {
2635 r.activity.mConfigChangeFlags |= configChanges;
2636 if (finishing) {
2637 r.activity.mFinished = true;
2638 }
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05002639 if (getNonConfigInstance) {
2640 r.activity.mChangingConfigurations = true;
2641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 if (!r.paused) {
2643 try {
2644 r.activity.mCalled = false;
2645 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002646 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 r.activity.getComponentName().getClassName());
2648 if (!r.activity.mCalled) {
2649 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002650 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 + " did not call through to super.onPause()");
2652 }
2653 } catch (SuperNotCalledException e) {
2654 throw e;
2655 } catch (Exception e) {
2656 if (!mInstrumentation.onException(r.activity, e)) {
2657 throw new RuntimeException(
2658 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002659 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 + ": " + e.toString(), e);
2661 }
2662 }
2663 r.paused = true;
2664 }
2665 if (!r.stopped) {
2666 try {
2667 r.activity.performStop();
2668 } catch (SuperNotCalledException e) {
2669 throw e;
2670 } catch (Exception e) {
2671 if (!mInstrumentation.onException(r.activity, e)) {
2672 throw new RuntimeException(
2673 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002674 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 + ": " + e.toString(), e);
2676 }
2677 }
2678 r.stopped = true;
2679 }
2680 if (getNonConfigInstance) {
2681 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002682 r.lastNonConfigurationInstances
2683 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 } catch (Exception e) {
2685 if (!mInstrumentation.onException(r.activity, e)) {
2686 throw new RuntimeException(
2687 "Unable to retain activity "
2688 + r.intent.getComponent().toShortString()
2689 + ": " + e.toString(), e);
2690 }
2691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 }
2693 try {
2694 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002695 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 if (!r.activity.mCalled) {
2697 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002698 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 " did not call through to super.onDestroy()");
2700 }
2701 if (r.window != null) {
2702 r.window.closeAllPanels();
2703 }
2704 } catch (SuperNotCalledException e) {
2705 throw e;
2706 } catch (Exception e) {
2707 if (!mInstrumentation.onException(r.activity, e)) {
2708 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002709 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2710 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
2712 }
2713 }
2714 mActivities.remove(token);
2715
2716 return r;
2717 }
2718
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002719 private static String safeToComponentShortString(Intent intent) {
2720 ComponentName component = intent.getComponent();
2721 return component == null ? "[Unknown]" : component.toShortString();
2722 }
2723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 private final void handleDestroyActivity(IBinder token, boolean finishing,
2725 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002726 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 configChanges, getNonConfigInstance);
2728 if (r != null) {
2729 WindowManager wm = r.activity.getWindowManager();
2730 View v = r.activity.mDecor;
2731 if (v != null) {
2732 if (r.activity.mVisibleFromServer) {
2733 mNumVisibleActivities--;
2734 }
2735 IBinder wtoken = v.getWindowToken();
2736 if (r.activity.mWindowAdded) {
2737 wm.removeViewImmediate(v);
2738 }
2739 if (wtoken != null) {
2740 WindowManagerImpl.getDefault().closeAll(wtoken,
2741 r.activity.getClass().getName(), "Activity");
2742 }
2743 r.activity.mDecor = null;
2744 }
2745 WindowManagerImpl.getDefault().closeAll(token,
2746 r.activity.getClass().getName(), "Activity");
2747
2748 // Mocked out contexts won't be participating in the normal
2749 // process lifecycle, but if we're running with a proper
2750 // ApplicationContext we need to have it tear down things
2751 // cleanly.
2752 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002753 if (c instanceof ContextImpl) {
2754 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 r.activity.getClass().getName(), "Activity");
2756 }
2757 }
2758 if (finishing) {
2759 try {
2760 ActivityManagerNative.getDefault().activityDestroyed(token);
2761 } catch (RemoteException ex) {
2762 // If the system process has died, it's game over for everyone.
2763 }
2764 }
2765 }
2766
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002767 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 // If we are getting ready to gc after going to the background, well
2769 // we are back active so skip it.
2770 unscheduleGcIdler();
2771
2772 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002773
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002774 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002775 + tmp.token + " with configChanges=0x"
2776 + Integer.toHexString(configChanges));
2777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 // First: make sure we have the most recent configuration and most
2779 // recent version of the activity, or skip it if some previous call
2780 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002781 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 int N = mRelaunchingActivities.size();
2783 IBinder token = tmp.token;
2784 tmp = null;
2785 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002786 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 if (r.token == token) {
2788 tmp = r;
2789 mRelaunchingActivities.remove(i);
2790 i--;
2791 N--;
2792 }
2793 }
Bob Leee5408332009-09-04 18:31:17 -07002794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002796 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 return;
2798 }
Bob Leee5408332009-09-04 18:31:17 -07002799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 if (mPendingConfiguration != null) {
2801 changedConfig = mPendingConfiguration;
2802 mPendingConfiguration = null;
2803 }
2804 }
Bob Leee5408332009-09-04 18:31:17 -07002805
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002806 if (tmp.createdConfig != null) {
2807 // If the activity manager is passing us its current config,
2808 // assume that is really what we want regardless of what we
2809 // may have pending.
2810 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002811 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2812 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2813 if (changedConfig == null
2814 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2815 changedConfig = tmp.createdConfig;
2816 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002817 }
2818 }
2819
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002820 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002821 + tmp.token + ": changedConfig=" + changedConfig);
2822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 // If there was a pending configuration change, execute it first.
2824 if (changedConfig != null) {
2825 handleConfigurationChanged(changedConfig);
2826 }
Bob Leee5408332009-09-04 18:31:17 -07002827
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002828 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002829 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 if (r == null) {
2831 return;
2832 }
Bob Leee5408332009-09-04 18:31:17 -07002833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002835 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 Bundle savedState = null;
2838 if (!r.paused) {
2839 savedState = performPauseActivity(r.token, false, true);
2840 }
Bob Leee5408332009-09-04 18:31:17 -07002841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 r.activity = null;
2845 r.window = null;
2846 r.hideForNow = false;
2847 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002848 // Merge any pending results and pending intents; don't just replace them
2849 if (tmp.pendingResults != null) {
2850 if (r.pendingResults == null) {
2851 r.pendingResults = tmp.pendingResults;
2852 } else {
2853 r.pendingResults.addAll(tmp.pendingResults);
2854 }
2855 }
2856 if (tmp.pendingIntents != null) {
2857 if (r.pendingIntents == null) {
2858 r.pendingIntents = tmp.pendingIntents;
2859 } else {
2860 r.pendingIntents.addAll(tmp.pendingIntents);
2861 }
2862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 r.startsNotResumed = tmp.startsNotResumed;
2864 if (savedState != null) {
2865 r.state = savedState;
2866 }
Bob Leee5408332009-09-04 18:31:17 -07002867
Christopher Tateb70f3df2009-04-07 16:07:59 -07002868 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 }
2870
2871 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002872 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 Bitmap thumbnail = createThumbnailBitmap(r);
2874 CharSequence description = null;
2875 try {
2876 description = r.activity.onCreateDescription();
2877 } catch (Exception e) {
2878 if (!mInstrumentation.onException(r.activity, e)) {
2879 throw new RuntimeException(
2880 "Unable to create description of activity "
2881 + r.intent.getComponent().toShortString()
2882 + ": " + e.toString(), e);
2883 }
2884 }
2885 //System.out.println("Reporting top thumbnail " + thumbnail);
2886 try {
2887 ActivityManagerNative.getDefault().reportThumbnail(
2888 token, thumbnail, description);
2889 } catch (RemoteException ex) {
2890 }
2891 }
2892
2893 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2894 boolean allActivities, Configuration newConfig) {
2895 ArrayList<ComponentCallbacks> callbacks
2896 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002899 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002901 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 Activity a = ar.activity;
2903 if (a != null) {
2904 if (!ar.activity.mFinished && (allActivities ||
2905 (a != null && !ar.paused))) {
2906 // If the activity is currently resumed, its configuration
2907 // needs to change right now.
2908 callbacks.add(a);
2909 } else if (newConfig != null) {
2910 // Otherwise, we will tell it about the change
2911 // the next time it is resumed or shown. Note that
2912 // the activity manager may, before then, decide the
2913 // activity needs to be destroyed to handle its new
2914 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002915 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002916 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 ar.newConfig = newConfig;
2918 }
2919 }
2920 }
2921 }
2922 if (mServices.size() > 0) {
2923 Iterator<Service> it = mServices.values().iterator();
2924 while (it.hasNext()) {
2925 callbacks.add(it.next());
2926 }
2927 }
2928 synchronized (mProviderMap) {
2929 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002930 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 while (it.hasNext()) {
2932 callbacks.add(it.next().mLocalProvider);
2933 }
2934 }
2935 }
2936 final int N = mAllApplications.size();
2937 for (int i=0; i<N; i++) {
2938 callbacks.add(mAllApplications.get(i));
2939 }
Bob Leee5408332009-09-04 18:31:17 -07002940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 return callbacks;
2942 }
Bob Leee5408332009-09-04 18:31:17 -07002943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 private final void performConfigurationChanged(
2945 ComponentCallbacks cb, Configuration config) {
2946 // Only for Activity objects, check that they actually call up to their
2947 // superclass implementation. ComponentCallbacks is an interface, so
2948 // we check the runtime type and act accordingly.
2949 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2950 if (activity != null) {
2951 activity.mCalled = false;
2952 }
Bob Leee5408332009-09-04 18:31:17 -07002953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 boolean shouldChangeConfig = false;
2955 if ((activity == null) || (activity.mCurrentConfig == null)) {
2956 shouldChangeConfig = true;
2957 } else {
Bob Leee5408332009-09-04 18:31:17 -07002958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 // If the new config is the same as the config this Activity
2960 // is already running with then don't bother calling
2961 // onConfigurationChanged
2962 int diff = activity.mCurrentConfig.diff(config);
2963 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 // If this activity doesn't handle any of the config changes
2966 // then don't bother calling onConfigurationChanged as we're
2967 // going to destroy it.
2968 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2969 shouldChangeConfig = true;
2970 }
2971 }
2972 }
Bob Leee5408332009-09-04 18:31:17 -07002973
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002974 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002975 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 if (shouldChangeConfig) {
2977 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 if (activity != null) {
2980 if (!activity.mCalled) {
2981 throw new SuperNotCalledException(
2982 "Activity " + activity.getLocalClassName() +
2983 " did not call through to super.onConfigurationChanged()");
2984 }
2985 activity.mConfigChangeFlags = 0;
2986 activity.mCurrentConfig = new Configuration(config);
2987 }
2988 }
2989 }
2990
Dianne Hackbornae078162010-03-18 11:29:37 -07002991 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002992 if (mResConfiguration == null) {
2993 mResConfiguration = new Configuration();
2994 }
2995 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002996 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002997 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002998 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002999 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003000 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003001 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07003002
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003003 // set it for java, this also affects newly created Resources
3004 if (config.locale != null) {
3005 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 }
Bob Leee5408332009-09-04 18:31:17 -07003007
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003008 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07003009
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003010 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003011 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003012
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003013 Iterator<WeakReference<Resources>> it =
3014 mActiveResources.values().iterator();
3015 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3016 // mActiveResources.entrySet().iterator();
3017 while (it.hasNext()) {
3018 WeakReference<Resources> v = it.next();
3019 Resources r = v.get();
3020 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003021 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003022 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003023 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003024 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003025 // + " " + r + ": " + r.getConfiguration());
3026 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003027 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003028 it.remove();
3029 }
3030 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003031
3032 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003033 }
3034
3035 final void handleConfigurationChanged(Configuration config) {
3036
3037 ArrayList<ComponentCallbacks> callbacks = null;
3038
3039 synchronized (mPackages) {
3040 if (mPendingConfiguration != null) {
3041 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3042 config = mPendingConfiguration;
3043 }
3044 mPendingConfiguration = null;
3045 }
3046
3047 if (config == null) {
3048 return;
3049 }
3050
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003051 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003052 + config);
3053
3054 applyConfigurationToResourcesLocked(config);
3055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 if (mConfiguration == null) {
3057 mConfiguration = new Configuration();
3058 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003059 if (!mConfiguration.isOtherSeqNewer(config)) {
3060 return;
3061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 callbacks = collectComponentCallbacksLocked(false, config);
3065 }
Bob Leee5408332009-09-04 18:31:17 -07003066
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003067 if (callbacks != null) {
3068 final int N = callbacks.size();
3069 for (int i=0; i<N; i++) {
3070 performConfigurationChanged(callbacks.get(i), config);
3071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 }
3073 }
3074
3075 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003076 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 if (r == null || r.activity == null) {
3078 return;
3079 }
Bob Leee5408332009-09-04 18:31:17 -07003080
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003081 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003082 + r.activityInfo.name);
3083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 performConfigurationChanged(r.activity, mConfiguration);
3085 }
3086
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003087 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003088 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003089 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003090 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3091 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003092 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003093 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003094 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003095 } finally {
3096 try {
3097 pcd.fd.close();
3098 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003099 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003100 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003101 }
3102 } else {
3103 Debug.stopMethodTracing();
3104 }
3105 }
Bob Leee5408332009-09-04 18:31:17 -07003106
Andy McFadden824c5102010-07-09 16:26:57 -07003107 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3108 if (managed) {
3109 try {
3110 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3111 } catch (IOException e) {
3112 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3113 + " -- can the process access this path?");
3114 } finally {
3115 try {
3116 dhd.fd.close();
3117 } catch (IOException e) {
3118 Slog.w(TAG, "Failure closing profile fd", e);
3119 }
3120 }
3121 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003122 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003123 }
3124 }
3125
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003126 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3127 boolean hasPkgInfo = false;
3128 if (packages != null) {
3129 for (int i=packages.length-1; i>=0; i--) {
3130 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3131 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003132 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003133 ref = mPackages.get(packages[i]);
3134 if (ref != null && ref.get() != null) {
3135 hasPkgInfo = true;
3136 } else {
3137 ref = mResourcePackages.get(packages[i]);
3138 if (ref != null && ref.get() != null) {
3139 hasPkgInfo = true;
3140 }
3141 }
3142 }
3143 mPackages.remove(packages[i]);
3144 mResourcePackages.remove(packages[i]);
3145 }
3146 }
3147 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3148 hasPkgInfo);
3149 }
3150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 final void handleLowMemory() {
3152 ArrayList<ComponentCallbacks> callbacks
3153 = new ArrayList<ComponentCallbacks>();
3154
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003155 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 callbacks = collectComponentCallbacksLocked(true, null);
3157 }
Bob Leee5408332009-09-04 18:31:17 -07003158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 final int N = callbacks.size();
3160 for (int i=0; i<N; i++) {
3161 callbacks.get(i).onLowMemory();
3162 }
3163
Chris Tatece229052009-03-25 16:44:52 -07003164 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3165 if (Process.myUid() != Process.SYSTEM_UID) {
3166 int sqliteReleased = SQLiteDatabase.releaseMemory();
3167 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3168 }
Bob Leee5408332009-09-04 18:31:17 -07003169
Mike Reedcaf0df12009-04-27 14:32:05 -04003170 // Ask graphics to free up as much as possible (font/image caches)
3171 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172
3173 BinderInternal.forceGc("mem");
3174 }
3175
3176 private final void handleBindApplication(AppBindData data) {
3177 mBoundApplication = data;
3178 mConfiguration = new Configuration(data.config);
3179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003181 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 android.ddm.DdmHandleAppName.setAppName(data.processName);
3183
3184 /*
3185 * Before spawning a new process, reset the time zone to be the system time zone.
3186 * This needs to be done because the system time zone could have changed after the
3187 * the spawning of this process. Without doing this this process would have the incorrect
3188 * system time zone.
3189 */
3190 TimeZone.setDefault(null);
3191
3192 /*
3193 * Initialize the default locale in this process for the reasons we set the time zone.
3194 */
3195 Locale.setDefault(data.config.locale);
3196
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003197 /*
3198 * Update the system configuration since its preloaded and might not
3199 * reflect configuration changes. The configuration object passed
3200 * in AppBindData can be safely assumed to be up to date
3201 */
3202 Resources.getSystem().updateConfiguration(mConfiguration, null);
3203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 data.info = getPackageInfoNoCheck(data.appInfo);
3205
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003206 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003207 * For system applications on userdebug/eng builds, log stack
3208 * traces of disk and network access to dropbox for analysis.
3209 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003210 if ((data.appInfo.flags &
3211 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003212 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3213 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003214 }
3215
3216 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003217 * Switch this process to density compatibility mode if needed.
3218 */
3219 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3220 == 0) {
3221 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3222 }
Bob Leee5408332009-09-04 18:31:17 -07003223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3225 // XXX should have option to change the port.
3226 Debug.changeDebugPort(8100);
3227 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003228 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 + " is waiting for the debugger on port 8100...");
3230
3231 IActivityManager mgr = ActivityManagerNative.getDefault();
3232 try {
3233 mgr.showWaitingForDebugger(mAppThread, true);
3234 } catch (RemoteException ex) {
3235 }
3236
3237 Debug.waitForDebugger();
3238
3239 try {
3240 mgr.showWaitingForDebugger(mAppThread, false);
3241 } catch (RemoteException ex) {
3242 }
3243
3244 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003245 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 + " can be debugged on port 8100...");
3247 }
3248 }
3249
3250 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003251 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 appContext.init(data.info, null, this);
3253 InstrumentationInfo ii = null;
3254 try {
3255 ii = appContext.getPackageManager().
3256 getInstrumentationInfo(data.instrumentationName, 0);
3257 } catch (PackageManager.NameNotFoundException e) {
3258 }
3259 if (ii == null) {
3260 throw new RuntimeException(
3261 "Unable to find instrumentation info for: "
3262 + data.instrumentationName);
3263 }
3264
3265 mInstrumentationAppDir = ii.sourceDir;
3266 mInstrumentationAppPackage = ii.packageName;
3267 mInstrumentedAppDir = data.info.getAppDir();
3268
3269 ApplicationInfo instrApp = new ApplicationInfo();
3270 instrApp.packageName = ii.packageName;
3271 instrApp.sourceDir = ii.sourceDir;
3272 instrApp.publicSourceDir = ii.publicSourceDir;
3273 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003274 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003275 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003277 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 instrContext.init(pi, null, this);
3279
3280 try {
3281 java.lang.ClassLoader cl = instrContext.getClassLoader();
3282 mInstrumentation = (Instrumentation)
3283 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3284 } catch (Exception e) {
3285 throw new RuntimeException(
3286 "Unable to instantiate instrumentation "
3287 + data.instrumentationName + ": " + e.toString(), e);
3288 }
3289
3290 mInstrumentation.init(this, instrContext, appContext,
3291 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3292
3293 if (data.profileFile != null && !ii.handleProfiling) {
3294 data.handlingProfiling = true;
3295 File file = new File(data.profileFile);
3296 file.getParentFile().mkdirs();
3297 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3298 }
3299
3300 try {
3301 mInstrumentation.onCreate(data.instrumentationArgs);
3302 }
3303 catch (Exception e) {
3304 throw new RuntimeException(
3305 "Exception thrown in onCreate() of "
3306 + data.instrumentationName + ": " + e.toString(), e);
3307 }
3308
3309 } else {
3310 mInstrumentation = new Instrumentation();
3311 }
3312
Christopher Tate181fafa2009-05-14 11:12:14 -07003313 // If the app is being launched for full backup or restore, bring it up in
3314 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003315 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 mInitialApplication = app;
3317
3318 List<ProviderInfo> providers = data.providers;
3319 if (providers != null) {
3320 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003321 // For process that contain content providers, we want to
3322 // ensure that the JIT is enabled "at some point".
3323 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 }
3325
3326 try {
3327 mInstrumentation.callApplicationOnCreate(app);
3328 } catch (Exception e) {
3329 if (!mInstrumentation.onException(app, e)) {
3330 throw new RuntimeException(
3331 "Unable to create application " + app.getClass().getName()
3332 + ": " + e.toString(), e);
3333 }
3334 }
3335 }
3336
3337 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3338 IActivityManager am = ActivityManagerNative.getDefault();
3339 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3340 Debug.stopMethodTracing();
3341 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003342 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 // + ", app thr: " + mAppThread);
3344 try {
3345 am.finishInstrumentation(mAppThread, resultCode, results);
3346 } catch (RemoteException ex) {
3347 }
3348 }
3349
3350 private final void installContentProviders(
3351 Context context, List<ProviderInfo> providers) {
3352 final ArrayList<IActivityManager.ContentProviderHolder> results =
3353 new ArrayList<IActivityManager.ContentProviderHolder>();
3354
3355 Iterator<ProviderInfo> i = providers.iterator();
3356 while (i.hasNext()) {
3357 ProviderInfo cpi = i.next();
3358 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003359 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 buf.append(cpi.authority);
3361 buf.append(": ");
3362 buf.append(cpi.name);
3363 Log.i(TAG, buf.toString());
3364 IContentProvider cp = installProvider(context, null, cpi, false);
3365 if (cp != null) {
3366 IActivityManager.ContentProviderHolder cph =
3367 new IActivityManager.ContentProviderHolder(cpi);
3368 cph.provider = cp;
3369 results.add(cph);
3370 // Don't ever unload this provider from the process.
3371 synchronized(mProviderMap) {
3372 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3373 }
3374 }
3375 }
3376
3377 try {
3378 ActivityManagerNative.getDefault().publishContentProviders(
3379 getApplicationThread(), results);
3380 } catch (RemoteException ex) {
3381 }
3382 }
3383
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003384 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003386 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 if (pr != null) {
3388 return pr.mProvider;
3389 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003390 return null;
3391 }
3392 }
3393
3394 private final IContentProvider getProvider(Context context, String name) {
3395 IContentProvider existing = getExistingProvider(context, name);
3396 if (existing != null) {
3397 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
3399
3400 IActivityManager.ContentProviderHolder holder = null;
3401 try {
3402 holder = ActivityManagerNative.getDefault().getContentProvider(
3403 getApplicationThread(), name);
3404 } catch (RemoteException ex) {
3405 }
3406 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003407 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 return null;
3409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410
3411 IContentProvider prov = installProvider(context, holder.provider,
3412 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003413 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 if (holder.noReleaseNeeded || holder.provider == null) {
3415 // We are not going to release the provider if it is an external
3416 // provider that doesn't care about being released, or if it is
3417 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003418 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 synchronized(mProviderMap) {
3420 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3421 }
3422 }
3423 return prov;
3424 }
3425
3426 public final IContentProvider acquireProvider(Context c, String name) {
3427 IContentProvider provider = getProvider(c, name);
3428 if(provider == null)
3429 return null;
3430 IBinder jBinder = provider.asBinder();
3431 synchronized(mProviderMap) {
3432 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3433 if(prc == null) {
3434 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3435 } else {
3436 prc.count++;
3437 } //end else
3438 } //end synchronized
3439 return provider;
3440 }
3441
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003442 public final IContentProvider acquireExistingProvider(Context c, String name) {
3443 IContentProvider provider = getExistingProvider(c, name);
3444 if(provider == null)
3445 return null;
3446 IBinder jBinder = provider.asBinder();
3447 synchronized(mProviderMap) {
3448 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3449 if(prc == null) {
3450 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3451 } else {
3452 prc.count++;
3453 } //end else
3454 } //end synchronized
3455 return provider;
3456 }
3457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 public final boolean releaseProvider(IContentProvider provider) {
3459 if(provider == null) {
3460 return false;
3461 }
3462 IBinder jBinder = provider.asBinder();
3463 synchronized(mProviderMap) {
3464 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3465 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003466 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 return false;
3468 } else {
3469 prc.count--;
3470 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003471 // Schedule the actual remove asynchronously, since we
3472 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003473 // TODO: it would be nice to post a delayed message, so
3474 // if we come back and need the same provider quickly
3475 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003476 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3477 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 } //end if
3479 } //end else
3480 } //end synchronized
3481 return true;
3482 }
3483
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003484 final void completeRemoveProvider(IContentProvider provider) {
3485 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003486 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003487 synchronized(mProviderMap) {
3488 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3489 if(prc != null && prc.count == 0) {
3490 mProviderRefCountMap.remove(jBinder);
3491 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003492 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003493 }
3494 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003495
3496 if (name != null) {
3497 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003498 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003499 "ActivityManagerNative.removeContentProvider(" + name);
3500 ActivityManagerNative.getDefault().removeContentProvider(
3501 getApplicationThread(), name);
3502 } catch (RemoteException e) {
3503 //do nothing content provider object is dead any way
3504 } //end catch
3505 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003506 }
3507
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003508 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003510 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 }
3512 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003514 String name = null;
3515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003517 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003519 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 IBinder myBinder = pr.mProvider.asBinder();
3521 if (myBinder == providerBinder) {
3522 //find if its published by this process itself
3523 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003524 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003525 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003527 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 "death recipient");
3529 //content provider is in another process
3530 myBinder.unlinkToDeath(pr, 0);
3531 iter.remove();
3532 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003533 if(name == null) {
3534 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 }
3536 } //end if myBinder
3537 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003538
3539 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 }
3541
3542 final void removeDeadProvider(String name, IContentProvider provider) {
3543 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003544 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003546 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003547 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003548 if (removed != null) {
3549 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 }
3552 }
3553 }
3554
3555 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003556 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003558 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003559 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003560 if (removed != null) {
3561 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 }
3564 }
3565
3566 private final IContentProvider installProvider(Context context,
3567 IContentProvider provider, ProviderInfo info, boolean noisy) {
3568 ContentProvider localProvider = null;
3569 if (provider == null) {
3570 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003571 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572 + info.name);
3573 }
3574 Context c = null;
3575 ApplicationInfo ai = info.applicationInfo;
3576 if (context.getPackageName().equals(ai.packageName)) {
3577 c = context;
3578 } else if (mInitialApplication != null &&
3579 mInitialApplication.getPackageName().equals(ai.packageName)) {
3580 c = mInitialApplication;
3581 } else {
3582 try {
3583 c = context.createPackageContext(ai.packageName,
3584 Context.CONTEXT_INCLUDE_CODE);
3585 } catch (PackageManager.NameNotFoundException e) {
3586 }
3587 }
3588 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003589 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 ai.packageName +
3591 " while loading content provider " +
3592 info.name);
3593 return null;
3594 }
3595 try {
3596 final java.lang.ClassLoader cl = c.getClassLoader();
3597 localProvider = (ContentProvider)cl.
3598 loadClass(info.name).newInstance();
3599 provider = localProvider.getIContentProvider();
3600 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003601 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 info.name + " from sourceDir " +
3603 info.applicationInfo.sourceDir);
3604 return null;
3605 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003606 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 TAG, "Instantiating local provider " + info.name);
3608 // XXX Need to create the correct context for this provider.
3609 localProvider.attachInfo(c, info);
3610 } catch (java.lang.Exception e) {
3611 if (!mInstrumentation.onException(null, e)) {
3612 throw new RuntimeException(
3613 "Unable to get provider " + info.name
3614 + ": " + e.toString(), e);
3615 }
3616 return null;
3617 }
3618 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003619 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 + info.name);
3621 }
3622
3623 synchronized (mProviderMap) {
3624 // Cache the pointer for the remote provider.
3625 String names[] = PATTERN_SEMICOLON.split(info.authority);
3626 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003627 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 localProvider);
3629 try {
3630 provider.asBinder().linkToDeath(pr, 0);
3631 mProviderMap.put(names[i], pr);
3632 } catch (RemoteException e) {
3633 return null;
3634 }
3635 }
3636 if (localProvider != null) {
3637 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003638 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 }
3640 }
3641
3642 return provider;
3643 }
3644
3645 private final void attach(boolean system) {
3646 sThreadLocal.set(this);
3647 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003649 ViewRoot.addFirstDrawHandler(new Runnable() {
3650 public void run() {
3651 ensureJitEnabled();
3652 }
3653 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3655 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3656 IActivityManager mgr = ActivityManagerNative.getDefault();
3657 try {
3658 mgr.attachApplication(mAppThread);
3659 } catch (RemoteException ex) {
3660 }
3661 } else {
3662 // Don't set application object here -- if the system crashes,
3663 // we can't display an alert, we just want to die die die.
3664 android.ddm.DdmHandleAppName.setAppName("system_process");
3665 try {
3666 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003667 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 context.init(getSystemContext().mPackageInfo, null, this);
3669 Application app = Instrumentation.newApplication(Application.class, context);
3670 mAllApplications.add(app);
3671 mInitialApplication = app;
3672 app.onCreate();
3673 } catch (Exception e) {
3674 throw new RuntimeException(
3675 "Unable to instantiate Application():" + e.toString(), e);
3676 }
3677 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003678
3679 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3680 public void onConfigurationChanged(Configuration newConfig) {
3681 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003682 // We need to apply this change to the resources
3683 // immediately, because upon returning the view
3684 // hierarchy will be informed about it.
3685 if (applyConfigurationToResourcesLocked(newConfig)) {
3686 // This actually changed the resources! Tell
3687 // everyone about it.
3688 if (mPendingConfiguration == null ||
3689 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3690 mPendingConfiguration = newConfig;
3691
3692 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3693 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003694 }
3695 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003696 }
3697 public void onLowMemory() {
3698 }
3699 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 }
3701
3702 private final void detach()
3703 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 sThreadLocal.set(null);
3705 }
3706
3707 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003708 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 ActivityThread thread = new ActivityThread();
3710 thread.attach(true);
3711 return thread;
3712 }
3713
3714 public final void installSystemProviders(List providers) {
3715 if (providers != null) {
3716 installContentProviders(mInitialApplication,
3717 (List<ProviderInfo>)providers);
3718 }
3719 }
3720
3721 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003722 SamplingProfilerIntegration.start();
3723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 Process.setArgV0("<pre-initialized>");
3725
3726 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003727 if (sMainThreadHandler == null) {
3728 sMainThreadHandler = new Handler();
3729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730
3731 ActivityThread thread = new ActivityThread();
3732 thread.attach(false);
3733
Dianne Hackborn287952c2010-09-22 22:34:31 -07003734 if (false) {
3735 Looper.myLooper().setMessageLogging(new
3736 LogPrinter(Log.DEBUG, "ActivityThread"));
3737 }
3738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 Looper.loop();
3740
3741 if (Process.supportsProcesses()) {
3742 throw new RuntimeException("Main thread loop unexpectedly exited");
3743 }
3744
3745 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003746 String name = (thread.mInitialApplication != null)
3747 ? thread.mInitialApplication.getPackageName()
3748 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003749 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 }
3751}