blob: 3cead1174da6e5b73921746e4222c5413856cbf1 [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;
Robert Greenwalt03595d02010-11-02 14:08:23 -070088import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import java.util.ArrayList;
90import java.util.HashMap;
91import java.util.Iterator;
92import java.util.List;
93import java.util.Locale;
94import java.util.Map;
95import java.util.TimeZone;
96import java.util.regex.Pattern;
97
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -080098import dalvik.system.CloseGuard;
Bob Leee5408332009-09-04 18:31:17 -070099import dalvik.system.SamplingProfiler;
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101final class SuperNotCalledException extends AndroidRuntimeException {
102 public SuperNotCalledException(String msg) {
103 super(msg);
104 }
105}
106
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700107final class RemoteServiceException extends AndroidRuntimeException {
108 public RemoteServiceException(String msg) {
109 super(msg);
110 }
111}
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113/**
114 * This manages the execution of the main thread in an
115 * application process, scheduling and executing activities,
116 * broadcasts, and other operations on it as the activity
117 * manager requests.
118 *
119 * {@hide}
120 */
121public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700122 /** @hide */
123 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700124 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700126 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700127 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700128 /** @hide */
129 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700130 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700131 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700132 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
134 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
135 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
136 private static final int LOG_ON_PAUSE_CALLED = 30021;
137 private static final int LOG_ON_RESUME_CALLED = 30022;
138
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700139 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700140
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700141 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700143 final ApplicationThread mAppThread = new ApplicationThread();
144 final Looper mLooper = Looper.myLooper();
145 final H mH = new H();
146 final HashMap<IBinder, ActivityClientRecord> mActivities
147 = new HashMap<IBinder, ActivityClientRecord>();
148 // List of new activities (via ActivityRecord.nextIdle) that should
149 // be reported when next we idle.
150 ActivityClientRecord mNewActivities = null;
151 // Number of activities that are currently visible on-screen.
152 int mNumVisibleActivities = 0;
153 final HashMap<IBinder, Service> mServices
154 = new HashMap<IBinder, Service>();
155 AppBindData mBoundApplication;
156 Configuration mConfiguration;
157 Configuration mResConfiguration;
158 Application mInitialApplication;
159 final ArrayList<Application> mAllApplications
160 = new ArrayList<Application>();
161 // set of instantiated backup agents, keyed by package name
162 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700163 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700164 Instrumentation mInstrumentation;
165 String mInstrumentationAppDir = null;
166 String mInstrumentationAppPackage = null;
167 String mInstrumentedAppDir = null;
168 boolean mSystemThread = false;
169 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700171 // These can be accessed by multiple threads; mPackages is the lock.
172 // XXX For now we keep around information about all packages we have
173 // seen, not removing entries from this map.
174 final HashMap<String, WeakReference<LoadedApk>> mPackages
175 = new HashMap<String, WeakReference<LoadedApk>>();
176 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
177 = new HashMap<String, WeakReference<LoadedApk>>();
178 Display mDisplay = null;
179 DisplayMetrics mDisplayMetrics = null;
180 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
181 = new HashMap<ResourcesKey, WeakReference<Resources> >();
182 final ArrayList<ActivityClientRecord> mRelaunchingActivities
183 = new ArrayList<ActivityClientRecord>();
184 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700186 // The lock of mProviderMap protects the following variables.
187 final HashMap<String, ProviderClientRecord> mProviderMap
188 = new HashMap<String, ProviderClientRecord>();
189 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
190 = new HashMap<IBinder, ProviderRefCount>();
191 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
192 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700194 final GcIdler mGcIdler = new GcIdler();
195 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700197 static Handler sMainThreadHandler; // set once in main()
198
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700199 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700201 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 Intent intent;
203 Bundle state;
204 Activity activity;
205 Window window;
206 Activity parent;
207 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700208 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 boolean paused;
210 boolean stopped;
211 boolean hideForNow;
212 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700213 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700214 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
216 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700217 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
219 List<ResultInfo> pendingResults;
220 List<Intent> pendingIntents;
221
222 boolean startsNotResumed;
223 boolean isForward;
224
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700225 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 parent = null;
227 embeddedID = null;
228 paused = false;
229 stopped = false;
230 hideForNow = false;
231 nextIdle = null;
232 }
233
234 public String toString() {
235 ComponentName componentName = intent.getComponent();
236 return "ActivityRecord{"
237 + Integer.toHexString(System.identityHashCode(this))
238 + " token=" + token + " " + (componentName == null
239 ? "no component name" : componentName.toShortString())
240 + "}";
241 }
242 }
243
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700244 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 final String mName;
246 final IContentProvider mProvider;
247 final ContentProvider mLocalProvider;
248
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700249 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 ContentProvider localProvider) {
251 mName = name;
252 mProvider = provider;
253 mLocalProvider = localProvider;
254 }
255
256 public void binderDied() {
257 removeDeadProvider(mName, mProvider);
258 }
259 }
260
261 private static final class NewIntentData {
262 List<Intent> intents;
263 IBinder token;
264 public String toString() {
265 return "NewIntentData{intents=" + intents + " token=" + token + "}";
266 }
267 }
268
Dianne Hackborne829fef2010-10-26 17:44:01 -0700269 private static final class ReceiverData extends BroadcastReceiver.PendingResult {
270 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
271 boolean ordered, boolean sticky, IBinder token) {
272 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
273 this.intent = intent;
274 }
275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 Intent intent;
277 ActivityInfo info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 public String toString() {
279 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700280 info.packageName + " resultCode=" + getResultCode()
281 + " resultData=" + getResultData() + " resultExtras="
282 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
284 }
285
Christopher Tate181fafa2009-05-14 11:12:14 -0700286 private static final class CreateBackupAgentData {
287 ApplicationInfo appInfo;
288 int backupMode;
289 public String toString() {
290 return "CreateBackupAgentData{appInfo=" + appInfo
291 + " backupAgent=" + appInfo.backupAgentName
292 + " mode=" + backupMode + "}";
293 }
294 }
Bob Leee5408332009-09-04 18:31:17 -0700295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 private static final class CreateServiceData {
297 IBinder token;
298 ServiceInfo info;
299 Intent intent;
300 public String toString() {
301 return "CreateServiceData{token=" + token + " className="
302 + info.name + " packageName=" + info.packageName
303 + " intent=" + intent + "}";
304 }
305 }
306
307 private static final class BindServiceData {
308 IBinder token;
309 Intent intent;
310 boolean rebind;
311 public String toString() {
312 return "BindServiceData{token=" + token + " intent=" + intent + "}";
313 }
314 }
315
316 private static final class ServiceArgsData {
317 IBinder token;
318 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700319 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 Intent args;
321 public String toString() {
322 return "ServiceArgsData{token=" + token + " startId=" + startId
323 + " args=" + args + "}";
324 }
325 }
326
327 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700328 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 String processName;
330 ApplicationInfo appInfo;
331 List<ProviderInfo> providers;
332 ComponentName instrumentationName;
333 String profileFile;
334 Bundle instrumentationArgs;
335 IInstrumentationWatcher instrumentationWatcher;
336 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700337 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 Configuration config;
339 boolean handlingProfiling;
340 public String toString() {
341 return "AppBindData{appInfo=" + appInfo + "}";
342 }
343 }
344
Dianne Hackborn625ac272010-09-17 18:29:22 -0700345 private static final class DumpComponentInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 FileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700347 IBinder token;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 String[] args;
349 boolean dumped;
350 }
351
352 private static final class ResultData {
353 IBinder token;
354 List<ResultInfo> results;
355 public String toString() {
356 return "ResultData{token=" + token + " results" + results + "}";
357 }
358 }
359
360 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800361 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 String what;
363 String who;
364 }
365
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700366 private static final class ProfilerControlData {
367 String path;
368 ParcelFileDescriptor fd;
369 }
370
Andy McFadden824c5102010-07-09 16:26:57 -0700371 private static final class DumpHeapData {
372 String path;
373 ParcelFileDescriptor fd;
374 }
375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 private final class ApplicationThread extends ApplicationThreadNative {
377 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
378 private static final String ONE_COUNT_COLUMN = "%17s %8d";
379 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700380 private static final String TWO_COUNT_COLUMNS_DB = "%20s %8d %20s %8d";
381 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 // Formatting for checkin service - update version if row format changes
384 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 public final void schedulePauseActivity(IBinder token, boolean finished,
387 boolean userLeaving, int configChanges) {
388 queueOrSendMessage(
389 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
390 token,
391 (userLeaving ? 1 : 0),
392 configChanges);
393 }
394
395 public final void scheduleStopActivity(IBinder token, boolean showWindow,
396 int configChanges) {
397 queueOrSendMessage(
398 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
399 token, 0, configChanges);
400 }
401
402 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
403 queueOrSendMessage(
404 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
405 token);
406 }
407
408 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
409 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
410 }
411
412 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
413 ResultData res = new ResultData();
414 res.token = token;
415 res.results = results;
416 queueOrSendMessage(H.SEND_RESULT, res);
417 }
418
419 // we use token to identify this activity without having to send the
420 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700421 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
423 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700424 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425
426 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700427 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 r.intent = intent;
429 r.activityInfo = info;
430 r.state = state;
431
432 r.pendingResults = pendingResults;
433 r.pendingIntents = pendingNewIntents;
434
435 r.startsNotResumed = notResumed;
436 r.isForward = isForward;
437
438 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
439 }
440
441 public final void scheduleRelaunchActivity(IBinder token,
442 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800443 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700444 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445
446 r.token = token;
447 r.pendingResults = pendingResults;
448 r.pendingIntents = pendingNewIntents;
449 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800450 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800452 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 mRelaunchingActivities.add(r);
454 }
Bob Leee5408332009-09-04 18:31:17 -0700455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
457 }
458
459 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
460 NewIntentData data = new NewIntentData();
461 data.intents = intents;
462 data.token = token;
463
464 queueOrSendMessage(H.NEW_INTENT, data);
465 }
466
467 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
468 int configChanges) {
469 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
470 configChanges);
471 }
472
473 public final void scheduleReceiver(Intent intent, ActivityInfo info,
474 int resultCode, String data, Bundle extras, boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700475 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
476 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 r.info = info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 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
Robert Greenwalt03595d02010-11-02 14:08:23 -0700590 public void clearDnsCache() {
591 // a non-standard API to get this to libcore
592 InetAddress.clearDnsCache();
593 }
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 public void processInBackground() {
596 mH.removeMessages(H.GC_WHEN_IDLE);
597 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
598 }
599
600 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700601 DumpComponentInfo data = new DumpComponentInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 data.fd = fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700603 data.token = servicetoken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 data.args = args;
605 data.dumped = false;
606 queueOrSendMessage(H.DUMP_SERVICE, data);
607 synchronized (data) {
608 while (!data.dumped) {
609 try {
610 data.wait();
611 } catch (InterruptedException e) {
612 // no need to do anything here, we will keep waiting until
613 // dumped is set
614 }
615 }
616 }
617 }
618
619 // This function exists to make sure all receiver dispatching is
620 // correctly ordered, since these are one-way calls and the binder driver
621 // applies transaction ordering per object for such calls.
622 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700623 int resultCode, String dataStr, Bundle extras, boolean ordered,
624 boolean sticky) throws RemoteException {
625 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 }
Bob Leee5408332009-09-04 18:31:17 -0700627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 public void scheduleLowMemory() {
629 queueOrSendMessage(H.LOW_MEMORY, null);
630 }
631
632 public void scheduleActivityConfigurationChanged(IBinder token) {
633 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
634 }
635
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700636 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
637 ProfilerControlData pcd = new ProfilerControlData();
638 pcd.path = path;
639 pcd.fd = fd;
640 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800641 }
642
Andy McFadden824c5102010-07-09 16:26:57 -0700643 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
644 DumpHeapData dhd = new DumpHeapData();
645 dhd.path = path;
646 dhd.fd = fd;
647 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
648 }
649
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700650 public void setSchedulingGroup(int group) {
651 // Note: do this immediately, since going into the foreground
652 // should happen regardless of what pending work we have to do
653 // and the activity manager will wait for us to report back that
654 // we are done before sending us to the background.
655 try {
656 Process.setProcessGroup(Process.myPid(), group);
657 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800658 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700659 }
660 }
Bob Leee5408332009-09-04 18:31:17 -0700661
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700662 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
663 Debug.getMemoryInfo(outInfo);
664 }
Bob Leee5408332009-09-04 18:31:17 -0700665
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700666 public void dispatchPackageBroadcast(int cmd, String[] packages) {
667 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
668 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700669
670 public void scheduleCrash(String msg) {
671 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
672 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700673
674 public void dumpActivity(FileDescriptor fd, IBinder activitytoken, String[] args) {
675 DumpComponentInfo data = new DumpComponentInfo();
676 data.fd = fd;
677 data.token = activitytoken;
678 data.args = args;
679 data.dumped = false;
680 queueOrSendMessage(H.DUMP_ACTIVITY, data);
681 synchronized (data) {
682 while (!data.dumped) {
683 try {
684 data.wait();
685 } catch (InterruptedException e) {
686 // no need to do anything here, we will keep waiting until
687 // dumped is set
688 }
689 }
690 }
691 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 @Override
694 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
695 long nativeMax = Debug.getNativeHeapSize() / 1024;
696 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
697 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
698
699 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
700 Debug.getMemoryInfo(memInfo);
701
702 final int nativeShared = memInfo.nativeSharedDirty;
703 final int dalvikShared = memInfo.dalvikSharedDirty;
704 final int otherShared = memInfo.otherSharedDirty;
705
706 final int nativePrivate = memInfo.nativePrivateDirty;
707 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
708 final int otherPrivate = memInfo.otherPrivateDirty;
709
710 Runtime runtime = Runtime.getRuntime();
711
712 long dalvikMax = runtime.totalMemory() / 1024;
713 long dalvikFree = runtime.freeMemory() / 1024;
714 long dalvikAllocated = dalvikMax - dalvikFree;
715 long viewInstanceCount = ViewDebug.getViewInstanceCount();
716 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700717 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
718 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 int globalAssetCount = AssetManager.getGlobalAssetCount();
720 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
721 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
722 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
723 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700724 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800726 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 // Check to see if we were called by checkin server. If so, print terse format.
729 boolean doCheckinFormat = false;
730 if (args != null) {
731 for (String arg : args) {
732 if ("-c".equals(arg)) doCheckinFormat = true;
733 }
734 }
Bob Leee5408332009-09-04 18:31:17 -0700735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 // For checkin, we print one long comma-separated list of values
737 if (doCheckinFormat) {
738 // NOTE: if you change anything significant below, also consider changing
739 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700740 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 // Header
744 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
745 pw.print(Process.myPid()); pw.print(',');
746 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 // Heap info - max
749 pw.print(nativeMax); pw.print(',');
750 pw.print(dalvikMax); pw.print(',');
751 pw.print("N/A,");
752 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 // Heap info - allocated
755 pw.print(nativeAllocated); pw.print(',');
756 pw.print(dalvikAllocated); pw.print(',');
757 pw.print("N/A,");
758 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 // Heap info - free
761 pw.print(nativeFree); pw.print(',');
762 pw.print(dalvikFree); pw.print(',');
763 pw.print("N/A,");
764 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 // Heap info - proportional set size
767 pw.print(memInfo.nativePss); pw.print(',');
768 pw.print(memInfo.dalvikPss); pw.print(',');
769 pw.print(memInfo.otherPss); pw.print(',');
770 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700773 pw.print(nativeShared); pw.print(',');
774 pw.print(dalvikShared); pw.print(',');
775 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700779 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 pw.print(dalvikPrivate); pw.print(',');
781 pw.print(otherPrivate); pw.print(',');
782 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 // Object counts
785 pw.print(viewInstanceCount); pw.print(',');
786 pw.print(viewRootInstanceCount); pw.print(',');
787 pw.print(appContextInstanceCount); pw.print(',');
788 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 pw.print(globalAssetCount); pw.print(',');
791 pw.print(globalAssetManagerCount); pw.print(',');
792 pw.print(binderLocalObjectCount); pw.print(',');
793 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 pw.print(binderDeathObjectCount); pw.print(',');
796 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 // SQL
799 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800800 pw.print(stats.memoryUsed / 1024); pw.print(',');
801 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
802 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
803 for (int i = 0; i < stats.dbStats.size(); i++) {
804 DbStats dbStats = stats.dbStats.get(i);
805 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700806 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800807 pw.print(',');
808 }
Bob Leee5408332009-09-04 18:31:17 -0700809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 return;
811 }
Bob Leee5408332009-09-04 18:31:17 -0700812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 // otherwise, show human-readable format
814 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
815 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
816 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
817 nativeAllocated + dalvikAllocated);
818 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
819 nativeFree + dalvikFree);
820
821 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
822 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
823
824 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
825 nativeShared + dalvikShared + otherShared);
826 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
827 nativePrivate + dalvikPrivate + otherPrivate);
828
829 pw.println(" ");
830 pw.println(" Objects");
831 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
832 viewRootInstanceCount);
833
834 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
835 "Activities:", activityInstanceCount);
836
837 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
838 "AssetManagers:", globalAssetManagerCount);
839
840 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
841 "Proxy Binders:", binderProxyObjectCount);
842 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
843
844 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 // SQLite mem info
847 pw.println(" ");
848 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700849 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800850 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700851 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
852 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800853 pw.println(" ");
854 int N = stats.dbStats.size();
855 if (N > 0) {
856 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700857 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
858 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800859 for (int i = 0; i < N; i++) {
860 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700861 printRow(pw, DB_INFO_FORMAT,
862 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
863 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
864 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
865 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800866 }
867 }
Bob Leee5408332009-09-04 18:31:17 -0700868
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700869 // Asset details.
870 String assetAlloc = AssetManager.getAssetAllocations();
871 if (assetAlloc != null) {
872 pw.println(" ");
873 pw.println(" Asset Allocations");
874 pw.print(assetAlloc);
875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 }
877
878 private void printRow(PrintWriter pw, String format, Object...objs) {
879 pw.println(String.format(format, objs));
880 }
881 }
882
883 private final class H extends Handler {
884 public static final int LAUNCH_ACTIVITY = 100;
885 public static final int PAUSE_ACTIVITY = 101;
886 public static final int PAUSE_ACTIVITY_FINISHING= 102;
887 public static final int STOP_ACTIVITY_SHOW = 103;
888 public static final int STOP_ACTIVITY_HIDE = 104;
889 public static final int SHOW_WINDOW = 105;
890 public static final int HIDE_WINDOW = 106;
891 public static final int RESUME_ACTIVITY = 107;
892 public static final int SEND_RESULT = 108;
893 public static final int DESTROY_ACTIVITY = 109;
894 public static final int BIND_APPLICATION = 110;
895 public static final int EXIT_APPLICATION = 111;
896 public static final int NEW_INTENT = 112;
897 public static final int RECEIVER = 113;
898 public static final int CREATE_SERVICE = 114;
899 public static final int SERVICE_ARGS = 115;
900 public static final int STOP_SERVICE = 116;
901 public static final int REQUEST_THUMBNAIL = 117;
902 public static final int CONFIGURATION_CHANGED = 118;
903 public static final int CLEAN_UP_CONTEXT = 119;
904 public static final int GC_WHEN_IDLE = 120;
905 public static final int BIND_SERVICE = 121;
906 public static final int UNBIND_SERVICE = 122;
907 public static final int DUMP_SERVICE = 123;
908 public static final int LOW_MEMORY = 124;
909 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
910 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800911 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700912 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700913 public static final int DESTROY_BACKUP_AGENT = 129;
914 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700915 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800916 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700917 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700918 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700919 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700920 public static final int DUMP_ACTIVITY = 136;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700922 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 switch (code) {
924 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
925 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
926 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
927 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
928 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
929 case SHOW_WINDOW: return "SHOW_WINDOW";
930 case HIDE_WINDOW: return "HIDE_WINDOW";
931 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
932 case SEND_RESULT: return "SEND_RESULT";
933 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
934 case BIND_APPLICATION: return "BIND_APPLICATION";
935 case EXIT_APPLICATION: return "EXIT_APPLICATION";
936 case NEW_INTENT: return "NEW_INTENT";
937 case RECEIVER: return "RECEIVER";
938 case CREATE_SERVICE: return "CREATE_SERVICE";
939 case SERVICE_ARGS: return "SERVICE_ARGS";
940 case STOP_SERVICE: return "STOP_SERVICE";
941 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
942 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
943 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
944 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
945 case BIND_SERVICE: return "BIND_SERVICE";
946 case UNBIND_SERVICE: return "UNBIND_SERVICE";
947 case DUMP_SERVICE: return "DUMP_SERVICE";
948 case LOW_MEMORY: return "LOW_MEMORY";
949 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
950 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800951 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700952 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
953 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700954 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700955 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800956 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700957 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700958 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -0700959 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -0700960 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
962 }
963 return "(unknown)";
964 }
965 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700966 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 switch (msg.what) {
968 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700969 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970
971 r.packageInfo = getPackageInfoNoCheck(
972 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700973 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 } break;
975 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700976 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 handleRelaunchActivity(r, msg.arg1);
978 } break;
979 case PAUSE_ACTIVITY:
980 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700981 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 break;
983 case PAUSE_ACTIVITY_FINISHING:
984 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
985 break;
986 case STOP_ACTIVITY_SHOW:
987 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
988 break;
989 case STOP_ACTIVITY_HIDE:
990 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
991 break;
992 case SHOW_WINDOW:
993 handleWindowVisibility((IBinder)msg.obj, true);
994 break;
995 case HIDE_WINDOW:
996 handleWindowVisibility((IBinder)msg.obj, false);
997 break;
998 case RESUME_ACTIVITY:
999 handleResumeActivity((IBinder)msg.obj, true,
1000 msg.arg1 != 0);
1001 break;
1002 case SEND_RESULT:
1003 handleSendResult((ResultData)msg.obj);
1004 break;
1005 case DESTROY_ACTIVITY:
1006 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1007 msg.arg2, false);
1008 break;
1009 case BIND_APPLICATION:
1010 AppBindData data = (AppBindData)msg.obj;
1011 handleBindApplication(data);
1012 break;
1013 case EXIT_APPLICATION:
1014 if (mInitialApplication != null) {
1015 mInitialApplication.onTerminate();
1016 }
1017 Looper.myLooper().quit();
1018 break;
1019 case NEW_INTENT:
1020 handleNewIntent((NewIntentData)msg.obj);
1021 break;
1022 case RECEIVER:
1023 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001024 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 break;
1026 case CREATE_SERVICE:
1027 handleCreateService((CreateServiceData)msg.obj);
1028 break;
1029 case BIND_SERVICE:
1030 handleBindService((BindServiceData)msg.obj);
1031 break;
1032 case UNBIND_SERVICE:
1033 handleUnbindService((BindServiceData)msg.obj);
1034 break;
1035 case SERVICE_ARGS:
1036 handleServiceArgs((ServiceArgsData)msg.obj);
1037 break;
1038 case STOP_SERVICE:
1039 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001040 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 break;
1042 case REQUEST_THUMBNAIL:
1043 handleRequestThumbnail((IBinder)msg.obj);
1044 break;
1045 case CONFIGURATION_CHANGED:
1046 handleConfigurationChanged((Configuration)msg.obj);
1047 break;
1048 case CLEAN_UP_CONTEXT:
1049 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1050 cci.context.performFinalCleanup(cci.who, cci.what);
1051 break;
1052 case GC_WHEN_IDLE:
1053 scheduleGcIdler();
1054 break;
1055 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001056 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 break;
1058 case LOW_MEMORY:
1059 handleLowMemory();
1060 break;
1061 case ACTIVITY_CONFIGURATION_CHANGED:
1062 handleActivityConfigurationChanged((IBinder)msg.obj);
1063 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001064 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001065 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001066 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001067 case CREATE_BACKUP_AGENT:
1068 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1069 break;
1070 case DESTROY_BACKUP_AGENT:
1071 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1072 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001073 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001074 Process.killProcess(Process.myPid());
1075 break;
1076 case REMOVE_PROVIDER:
1077 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001078 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001079 case ENABLE_JIT:
1080 ensureJitEnabled();
1081 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001082 case DISPATCH_PACKAGE_BROADCAST:
1083 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1084 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001085 case SCHEDULE_CRASH:
1086 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001087 case DUMP_HEAP:
1088 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1089 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001090 case DUMP_ACTIVITY:
1091 handleDumpActivity((DumpComponentInfo)msg.obj);
1092 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001094 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 }
Bob Leee5408332009-09-04 18:31:17 -07001096
1097 void maybeSnapshot() {
1098 if (mBoundApplication != null) {
Sen Hubde75702010-05-28 01:54:03 -07001099 // convert the *private* ActivityThread.PackageInfo to *public* known
1100 // android.content.pm.PackageInfo
1101 String packageName = mBoundApplication.info.mPackageName;
1102 android.content.pm.PackageInfo packageInfo = null;
1103 try {
1104 Context context = getSystemContext();
1105 if(context == null) {
1106 Log.e(TAG, "cannot get a valid context");
1107 return;
1108 }
1109 PackageManager pm = context.getPackageManager();
1110 if(pm == null) {
1111 Log.e(TAG, "cannot get a valid PackageManager");
1112 return;
1113 }
1114 packageInfo = pm.getPackageInfo(
1115 packageName, PackageManager.GET_ACTIVITIES);
1116 } catch (NameNotFoundException e) {
1117 Log.e(TAG, "cannot get package info for " + packageName, e);
1118 }
1119 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001120 }
1121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 }
1123
1124 private final class Idler implements MessageQueue.IdleHandler {
1125 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001126 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 if (a != null) {
1128 mNewActivities = null;
1129 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001130 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001132 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 TAG, "Reporting idle of " + a +
1134 " finished=" +
1135 (a.activity != null ? a.activity.mFinished : false));
1136 if (a.activity != null && !a.activity.mFinished) {
1137 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001138 am.activityIdle(a.token, a.createdConfig);
1139 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 } catch (RemoteException ex) {
1141 }
1142 }
1143 prev = a;
1144 a = a.nextIdle;
1145 prev.nextIdle = null;
1146 } while (a != null);
1147 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001148 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 return false;
1150 }
1151 }
1152
1153 final class GcIdler implements MessageQueue.IdleHandler {
1154 public final boolean queueIdle() {
1155 doGcIfNeeded();
1156 return false;
1157 }
1158 }
1159
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001160 private final static class ResourcesKey {
1161 final private String mResDir;
1162 final private float mScale;
1163 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001164
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001165 ResourcesKey(String resDir, float scale) {
1166 mResDir = resDir;
1167 mScale = scale;
1168 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1169 }
Bob Leee5408332009-09-04 18:31:17 -07001170
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001171 @Override
1172 public int hashCode() {
1173 return mHash;
1174 }
1175
1176 @Override
1177 public boolean equals(Object obj) {
1178 if (!(obj instanceof ResourcesKey)) {
1179 return false;
1180 }
1181 ResourcesKey peer = (ResourcesKey) obj;
1182 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1183 }
1184 }
1185
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001186 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001187 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001190 public static final String currentPackageName() {
1191 ActivityThread am = currentActivityThread();
1192 return (am != null && am.mBoundApplication != null)
1193 ? am.mBoundApplication.processName : null;
1194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001196 public static final Application currentApplication() {
1197 ActivityThread am = currentActivityThread();
1198 return am != null ? am.mInitialApplication : null;
1199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001201 public static IPackageManager getPackageManager() {
1202 if (sPackageManager != null) {
1203 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1204 return sPackageManager;
1205 }
1206 IBinder b = ServiceManager.getService("package");
1207 //Slog.v("PackageManager", "default service binder = " + b);
1208 sPackageManager = IPackageManager.Stub.asInterface(b);
1209 //Slog.v("PackageManager", "default service = " + sPackageManager);
1210 return sPackageManager;
1211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001213 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1214 if (mDisplayMetrics != null && !forceUpdate) {
1215 return mDisplayMetrics;
1216 }
1217 if (mDisplay == null) {
1218 WindowManager wm = WindowManagerImpl.getDefault();
1219 mDisplay = wm.getDefaultDisplay();
1220 }
1221 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1222 mDisplay.getMetrics(metrics);
1223 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1224 // + metrics.heightPixels + " den=" + metrics.density
1225 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1226 return metrics;
1227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001229 /**
1230 * Creates the top level Resources for applications with the given compatibility info.
1231 *
1232 * @param resDir the resource directory.
1233 * @param compInfo the compability info. It will use the default compatibility info when it's
1234 * null.
1235 */
1236 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1237 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1238 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001240 // Resources is app scale dependent.
1241 if (false) {
1242 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1243 + compInfo.applicationScale);
1244 }
1245 WeakReference<Resources> wr = mActiveResources.get(key);
1246 r = wr != null ? wr.get() : null;
1247 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1248 if (r != null && r.getAssets().isUpToDate()) {
1249 if (false) {
1250 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1251 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1252 }
1253 return r;
1254 }
1255 }
1256
1257 //if (r != null) {
1258 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1259 // + r + " " + resDir);
1260 //}
1261
1262 AssetManager assets = new AssetManager();
1263 if (assets.addAssetPath(resDir) == 0) {
1264 return null;
1265 }
1266
1267 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1268 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1269 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1270 if (false) {
1271 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1272 + r.getConfiguration() + " appScale="
1273 + r.getCompatibilityInfo().applicationScale);
1274 }
1275
1276 synchronized (mPackages) {
1277 WeakReference<Resources> wr = mActiveResources.get(key);
1278 Resources existing = wr != null ? wr.get() : null;
1279 if (existing != null && existing.getAssets().isUpToDate()) {
1280 // Someone else already created the resources while we were
1281 // unlocked; go ahead and use theirs.
1282 r.getAssets().close();
1283 return existing;
1284 }
1285
1286 // XXX need to remove entries when weak references go away
1287 mActiveResources.put(key, new WeakReference<Resources>(r));
1288 return r;
1289 }
1290 }
1291
1292 /**
1293 * Creates the top level resources for the given package.
1294 */
1295 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1296 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1297 }
1298
1299 final Handler getHandler() {
1300 return mH;
1301 }
1302
1303 public final LoadedApk getPackageInfo(String packageName, int flags) {
1304 synchronized (mPackages) {
1305 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1307 ref = mPackages.get(packageName);
1308 } else {
1309 ref = mResourcePackages.get(packageName);
1310 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001311 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001312 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001313 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1314 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 if (packageInfo != null && (packageInfo.mResources == null
1316 || packageInfo.mResources.getAssets().isUpToDate())) {
1317 if (packageInfo.isSecurityViolation()
1318 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1319 throw new SecurityException(
1320 "Requesting code from " + packageName
1321 + " to be run in process "
1322 + mBoundApplication.processName
1323 + "/" + mBoundApplication.appInfo.uid);
1324 }
1325 return packageInfo;
1326 }
1327 }
1328
1329 ApplicationInfo ai = null;
1330 try {
1331 ai = getPackageManager().getApplicationInfo(packageName,
1332 PackageManager.GET_SHARED_LIBRARY_FILES);
1333 } catch (RemoteException e) {
1334 }
1335
1336 if (ai != null) {
1337 return getPackageInfo(ai, flags);
1338 }
1339
1340 return null;
1341 }
1342
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001343 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1345 boolean securityViolation = includeCode && ai.uid != 0
1346 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1347 ? ai.uid != mBoundApplication.appInfo.uid : true);
1348 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1349 |Context.CONTEXT_IGNORE_SECURITY))
1350 == Context.CONTEXT_INCLUDE_CODE) {
1351 if (securityViolation) {
1352 String msg = "Requesting code from " + ai.packageName
1353 + " (with uid " + ai.uid + ")";
1354 if (mBoundApplication != null) {
1355 msg = msg + " to be run in process "
1356 + mBoundApplication.processName + " (with uid "
1357 + mBoundApplication.appInfo.uid + ")";
1358 }
1359 throw new SecurityException(msg);
1360 }
1361 }
1362 return getPackageInfo(ai, null, securityViolation, includeCode);
1363 }
1364
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001365 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 return getPackageInfo(ai, null, false, true);
1367 }
1368
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001369 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1371 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001372 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 if (includeCode) {
1374 ref = mPackages.get(aInfo.packageName);
1375 } else {
1376 ref = mResourcePackages.get(aInfo.packageName);
1377 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001378 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 if (packageInfo == null || (packageInfo.mResources != null
1380 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001381 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 : "Loading resource-only package ") + aInfo.packageName
1383 + " (in " + (mBoundApplication != null
1384 ? mBoundApplication.processName : null)
1385 + ")");
1386 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001387 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 securityViolation, includeCode &&
1389 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1390 if (includeCode) {
1391 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001392 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 } else {
1394 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001395 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
1397 }
1398 return packageInfo;
1399 }
1400 }
1401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 ActivityThread() {
1403 }
1404
1405 public ApplicationThread getApplicationThread()
1406 {
1407 return mAppThread;
1408 }
1409
1410 public Instrumentation getInstrumentation()
1411 {
1412 return mInstrumentation;
1413 }
1414
1415 public Configuration getConfiguration() {
1416 return mConfiguration;
1417 }
1418
1419 public boolean isProfiling() {
1420 return mBoundApplication != null && mBoundApplication.profileFile != null;
1421 }
1422
1423 public String getProfileFilePath() {
1424 return mBoundApplication.profileFile;
1425 }
1426
1427 public Looper getLooper() {
1428 return mLooper;
1429 }
1430
1431 public Application getApplication() {
1432 return mInitialApplication;
1433 }
Bob Leee5408332009-09-04 18:31:17 -07001434
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001435 public String getProcessName() {
1436 return mBoundApplication.processName;
1437 }
Bob Leee5408332009-09-04 18:31:17 -07001438
Dianne Hackborn21556372010-02-04 16:34:40 -08001439 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 synchronized (this) {
1441 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001442 ContextImpl context =
1443 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001444 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 context.init(info, null, this);
1446 context.getResources().updateConfiguration(
1447 getConfiguration(), getDisplayMetricsLocked(false));
1448 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001449 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 // + ": " + context.getResources().getConfiguration());
1451 }
1452 }
1453 return mSystemContext;
1454 }
1455
Mike Cleron432b7132009-09-24 15:28:29 -07001456 public void installSystemApplicationInfo(ApplicationInfo info) {
1457 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001458 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001459 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001460 }
1461 }
1462
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001463 void ensureJitEnabled() {
1464 if (!mJitEnabled) {
1465 mJitEnabled = true;
1466 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1467 }
1468 }
1469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 void scheduleGcIdler() {
1471 if (!mGcIdlerScheduled) {
1472 mGcIdlerScheduled = true;
1473 Looper.myQueue().addIdleHandler(mGcIdler);
1474 }
1475 mH.removeMessages(H.GC_WHEN_IDLE);
1476 }
1477
1478 void unscheduleGcIdler() {
1479 if (mGcIdlerScheduled) {
1480 mGcIdlerScheduled = false;
1481 Looper.myQueue().removeIdleHandler(mGcIdler);
1482 }
1483 mH.removeMessages(H.GC_WHEN_IDLE);
1484 }
1485
1486 void doGcIfNeeded() {
1487 mGcIdlerScheduled = false;
1488 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001489 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 // + "m now=" + now);
1491 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001492 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 BinderInternal.forceGc("bg");
1494 }
1495 }
1496
1497 public final ActivityInfo resolveActivityInfo(Intent intent) {
1498 ActivityInfo aInfo = intent.resolveActivityInfo(
1499 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1500 if (aInfo == null) {
1501 // Throw an exception.
1502 Instrumentation.checkStartActivityResult(
1503 IActivityManager.START_CLASS_NOT_FOUND, intent);
1504 }
1505 return aInfo;
1506 }
Bob Leee5408332009-09-04 18:31:17 -07001507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001510 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001511 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001513 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 r.intent = intent;
1515 r.state = state;
1516 r.parent = parent;
1517 r.embeddedID = id;
1518 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001519 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 if (localLOGV) {
1521 ComponentName compname = intent.getComponent();
1522 String name;
1523 if (compname != null) {
1524 name = compname.toShortString();
1525 } else {
1526 name = "(Intent " + intent + ").getComponent() returned null";
1527 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001528 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 + ", comp=" + name
1530 + ", token=" + token);
1531 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001532 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534
1535 public final Activity getActivity(IBinder token) {
1536 return mActivities.get(token).activity;
1537 }
1538
1539 public final void sendActivityResult(
1540 IBinder token, String id, int requestCode,
1541 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001542 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001543 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1545 list.add(new ResultInfo(id, requestCode, resultCode, data));
1546 mAppThread.scheduleSendResult(token, list);
1547 }
1548
1549 // if the thread hasn't started yet, we don't have the handler, so just
1550 // save the messages until we're ready.
1551 private final void queueOrSendMessage(int what, Object obj) {
1552 queueOrSendMessage(what, obj, 0, 0);
1553 }
1554
1555 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1556 queueOrSendMessage(what, obj, arg1, 0);
1557 }
1558
1559 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1560 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001561 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1563 + ": " + arg1 + " / " + obj);
1564 Message msg = Message.obtain();
1565 msg.what = what;
1566 msg.obj = obj;
1567 msg.arg1 = arg1;
1568 msg.arg2 = arg2;
1569 mH.sendMessage(msg);
1570 }
1571 }
1572
Dianne Hackborn21556372010-02-04 16:34:40 -08001573 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 String what) {
1575 ContextCleanupInfo cci = new ContextCleanupInfo();
1576 cci.context = context;
1577 cci.who = who;
1578 cci.what = what;
1579 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1580 }
1581
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001582 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1584
1585 ActivityInfo aInfo = r.activityInfo;
1586 if (r.packageInfo == null) {
1587 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1588 Context.CONTEXT_INCLUDE_CODE);
1589 }
Bob Leee5408332009-09-04 18:31:17 -07001590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 ComponentName component = r.intent.getComponent();
1592 if (component == null) {
1593 component = r.intent.resolveActivity(
1594 mInitialApplication.getPackageManager());
1595 r.intent.setComponent(component);
1596 }
1597
1598 if (r.activityInfo.targetActivity != null) {
1599 component = new ComponentName(r.activityInfo.packageName,
1600 r.activityInfo.targetActivity);
1601 }
1602
1603 Activity activity = null;
1604 try {
1605 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1606 activity = mInstrumentation.newActivity(
1607 cl, component.getClassName(), r.intent);
1608 r.intent.setExtrasClassLoader(cl);
1609 if (r.state != null) {
1610 r.state.setClassLoader(cl);
1611 }
1612 } catch (Exception e) {
1613 if (!mInstrumentation.onException(activity, e)) {
1614 throw new RuntimeException(
1615 "Unable to instantiate activity " + component
1616 + ": " + e.toString(), e);
1617 }
1618 }
1619
1620 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001621 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001622
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001623 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1624 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 TAG, r + ": app=" + app
1626 + ", appName=" + app.getPackageName()
1627 + ", pkg=" + r.packageInfo.getPackageName()
1628 + ", comp=" + r.intent.getComponent().toShortString()
1629 + ", dir=" + r.packageInfo.getAppDir());
1630
1631 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001632 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 appContext.init(r.packageInfo, r.token, this);
1634 appContext.setOuterContext(activity);
1635 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1636 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001637 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001638 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001639 activity.attach(appContext, this, getInstrumentation(), r.token,
1640 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001641 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001642
Christopher Tateb70f3df2009-04-07 16:07:59 -07001643 if (customIntent != null) {
1644 activity.mIntent = customIntent;
1645 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001646 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 activity.mStartedActivity = false;
1648 int theme = r.activityInfo.getThemeResource();
1649 if (theme != 0) {
1650 activity.setTheme(theme);
1651 }
1652
1653 activity.mCalled = false;
1654 mInstrumentation.callActivityOnCreate(activity, r.state);
1655 if (!activity.mCalled) {
1656 throw new SuperNotCalledException(
1657 "Activity " + r.intent.getComponent().toShortString() +
1658 " did not call through to super.onCreate()");
1659 }
1660 r.activity = activity;
1661 r.stopped = true;
1662 if (!r.activity.mFinished) {
1663 activity.performStart();
1664 r.stopped = false;
1665 }
1666 if (!r.activity.mFinished) {
1667 if (r.state != null) {
1668 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1669 }
1670 }
1671 if (!r.activity.mFinished) {
1672 activity.mCalled = false;
1673 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1674 if (!activity.mCalled) {
1675 throw new SuperNotCalledException(
1676 "Activity " + r.intent.getComponent().toShortString() +
1677 " did not call through to super.onPostCreate()");
1678 }
1679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 }
1681 r.paused = true;
1682
1683 mActivities.put(r.token, r);
1684
1685 } catch (SuperNotCalledException e) {
1686 throw e;
1687
1688 } catch (Exception e) {
1689 if (!mInstrumentation.onException(activity, e)) {
1690 throw new RuntimeException(
1691 "Unable to start activity " + component
1692 + ": " + e.toString(), e);
1693 }
1694 }
1695
1696 return activity;
1697 }
1698
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001699 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 // If we are getting ready to gc after going to the background, well
1701 // we are back active so skip it.
1702 unscheduleGcIdler();
1703
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001704 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001706 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707
1708 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001709 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001710 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 handleResumeActivity(r.token, false, r.isForward);
1712
1713 if (!r.activity.mFinished && r.startsNotResumed) {
1714 // The activity manager actually wants this one to start out
1715 // paused, because it needs to be visible but isn't in the
1716 // foreground. We accomplish this by going through the
1717 // normal startup (because activities expect to go through
1718 // onResume() the first time they run, before their window
1719 // is displayed), and then pausing it. However, in this case
1720 // we do -not- need to do the full pause cycle (of freezing
1721 // and such) because the activity manager assumes it can just
1722 // retain the current state it has.
1723 try {
1724 r.activity.mCalled = false;
1725 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001726 // We need to keep around the original state, in case
1727 // we need to be created again.
1728 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 if (!r.activity.mCalled) {
1730 throw new SuperNotCalledException(
1731 "Activity " + r.intent.getComponent().toShortString() +
1732 " did not call through to super.onPause()");
1733 }
1734
1735 } catch (SuperNotCalledException e) {
1736 throw e;
1737
1738 } catch (Exception e) {
1739 if (!mInstrumentation.onException(r.activity, e)) {
1740 throw new RuntimeException(
1741 "Unable to pause activity "
1742 + r.intent.getComponent().toShortString()
1743 + ": " + e.toString(), e);
1744 }
1745 }
1746 r.paused = true;
1747 }
1748 } else {
1749 // If there was an error, for any reason, tell the activity
1750 // manager to stop us.
1751 try {
1752 ActivityManagerNative.getDefault()
1753 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1754 } catch (RemoteException ex) {
1755 }
1756 }
1757 }
1758
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001759 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 List<Intent> intents) {
1761 final int N = intents.size();
1762 for (int i=0; i<N; i++) {
1763 Intent intent = intents.get(i);
1764 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001765 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1767 }
1768 }
1769
1770 public final void performNewIntents(IBinder token,
1771 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001772 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 if (r != null) {
1774 final boolean resumed = !r.paused;
1775 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001776 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 mInstrumentation.callActivityOnPause(r.activity);
1778 }
1779 deliverNewIntents(r, intents);
1780 if (resumed) {
1781 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001782 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 }
1784 }
1785 }
Bob Leee5408332009-09-04 18:31:17 -07001786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 private final void handleNewIntent(NewIntentData data) {
1788 performNewIntents(data.token, data.intents);
1789 }
1790
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001791 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
1792
1793 /**
1794 * Return the Intent that's currently being handled by a
1795 * BroadcastReceiver on this thread, or null if none.
1796 * @hide
1797 */
1798 public static Intent getIntentBeingBroadcast() {
1799 return sCurrentBroadcastIntent.get();
1800 }
1801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 private final void handleReceiver(ReceiverData data) {
1803 // If we are getting ready to gc after going to the background, well
1804 // we are back active so skip it.
1805 unscheduleGcIdler();
1806
1807 String component = data.intent.getComponent().getClassName();
1808
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001809 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 data.info.applicationInfo);
1811
1812 IActivityManager mgr = ActivityManagerNative.getDefault();
1813
1814 BroadcastReceiver receiver = null;
1815 try {
1816 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1817 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001818 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1820 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001821 if (DEBUG_BROADCAST) Slog.i(TAG,
1822 "Finishing failed broadcast to " + data.intent.getComponent());
1823 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 throw new RuntimeException(
1825 "Unable to instantiate receiver " + component
1826 + ": " + e.toString(), e);
1827 }
1828
1829 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001830 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001831
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001832 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 TAG, "Performing receive of " + data.intent
1834 + ": app=" + app
1835 + ", appName=" + app.getPackageName()
1836 + ", pkg=" + packageInfo.getPackageName()
1837 + ", comp=" + data.intent.getComponent().toShortString()
1838 + ", dir=" + packageInfo.getAppDir());
1839
Dianne Hackborn21556372010-02-04 16:34:40 -08001840 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001841 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001842 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 receiver.onReceive(context.getReceiverRestrictedContext(),
1844 data.intent);
1845 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001846 if (DEBUG_BROADCAST) Slog.i(TAG,
1847 "Finishing failed broadcast to " + data.intent.getComponent());
1848 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 if (!mInstrumentation.onException(receiver, e)) {
1850 throw new RuntimeException(
1851 "Unable to start receiver " + component
1852 + ": " + e.toString(), e);
1853 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001854 } finally {
1855 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
1857
Dianne Hackborne829fef2010-10-26 17:44:01 -07001858 if (receiver.getPendingResult() != null) {
1859 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861 }
1862
Christopher Tate181fafa2009-05-14 11:12:14 -07001863 // Instantiate a BackupAgent and tell it that it's alive
1864 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001865 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001866
1867 // no longer idle; we have backup work to do
1868 unscheduleGcIdler();
1869
1870 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001871 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001872 String packageName = packageInfo.mPackageName;
1873 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001874 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001875 + " already exists");
1876 return;
1877 }
Bob Leee5408332009-09-04 18:31:17 -07001878
Christopher Tate181fafa2009-05-14 11:12:14 -07001879 BackupAgent agent = null;
1880 String classname = data.appInfo.backupAgentName;
1881 if (classname == null) {
1882 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001883 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001884 + packageName);
1885 return;
1886 }
1887 classname = "android.app.FullBackupAgent";
1888 }
1889 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001890 IBinder binder = null;
1891 try {
1892 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1893 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1894
1895 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001896 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001897 + data.appInfo.backupAgentName);
1898
Dianne Hackborn21556372010-02-04 16:34:40 -08001899 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001900 context.init(packageInfo, null, this);
1901 context.setOuterContext(agent);
1902 agent.attach(context);
1903
1904 agent.onCreate();
1905 binder = agent.onBind();
1906 mBackupAgents.put(packageName, agent);
1907 } catch (Exception e) {
1908 // If this is during restore, fail silently; otherwise go
1909 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001910 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001911 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1912 throw e;
1913 }
1914 // falling through with 'binder' still null
1915 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001916
1917 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001918 try {
1919 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1920 } catch (RemoteException e) {
1921 // nothing to do.
1922 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001923 } catch (Exception e) {
1924 throw new RuntimeException("Unable to create BackupAgent "
1925 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1926 }
1927 }
1928
1929 // Tear down a BackupAgent
1930 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001931 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001932
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001933 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001934 String packageName = packageInfo.mPackageName;
1935 BackupAgent agent = mBackupAgents.get(packageName);
1936 if (agent != null) {
1937 try {
1938 agent.onDestroy();
1939 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001940 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001941 e.printStackTrace();
1942 }
1943 mBackupAgents.remove(packageName);
1944 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001945 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001946 }
1947 }
1948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 private final void handleCreateService(CreateServiceData data) {
1950 // If we are getting ready to gc after going to the background, well
1951 // we are back active so skip it.
1952 unscheduleGcIdler();
1953
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001954 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 data.info.applicationInfo);
1956 Service service = null;
1957 try {
1958 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1959 service = (Service) cl.loadClass(data.info.name).newInstance();
1960 } catch (Exception e) {
1961 if (!mInstrumentation.onException(service, e)) {
1962 throw new RuntimeException(
1963 "Unable to instantiate service " + data.info.name
1964 + ": " + e.toString(), e);
1965 }
1966 }
1967
1968 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001969 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970
Dianne Hackborn21556372010-02-04 16:34:40 -08001971 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 context.init(packageInfo, null, this);
1973
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001974 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 context.setOuterContext(service);
1976 service.attach(context, this, data.info.name, data.token, app,
1977 ActivityManagerNative.getDefault());
1978 service.onCreate();
1979 mServices.put(data.token, service);
1980 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001981 ActivityManagerNative.getDefault().serviceDoneExecuting(
1982 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 } catch (RemoteException e) {
1984 // nothing to do.
1985 }
1986 } catch (Exception e) {
1987 if (!mInstrumentation.onException(service, e)) {
1988 throw new RuntimeException(
1989 "Unable to create service " + data.info.name
1990 + ": " + e.toString(), e);
1991 }
1992 }
1993 }
1994
1995 private final void handleBindService(BindServiceData data) {
1996 Service s = mServices.get(data.token);
1997 if (s != null) {
1998 try {
1999 data.intent.setExtrasClassLoader(s.getClassLoader());
2000 try {
2001 if (!data.rebind) {
2002 IBinder binder = s.onBind(data.intent);
2003 ActivityManagerNative.getDefault().publishService(
2004 data.token, data.intent, binder);
2005 } else {
2006 s.onRebind(data.intent);
2007 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002008 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002010 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 } catch (RemoteException ex) {
2012 }
2013 } catch (Exception e) {
2014 if (!mInstrumentation.onException(s, e)) {
2015 throw new RuntimeException(
2016 "Unable to bind to service " + s
2017 + " with " + data.intent + ": " + e.toString(), e);
2018 }
2019 }
2020 }
2021 }
2022
2023 private final void handleUnbindService(BindServiceData data) {
2024 Service s = mServices.get(data.token);
2025 if (s != null) {
2026 try {
2027 data.intent.setExtrasClassLoader(s.getClassLoader());
2028 boolean doRebind = s.onUnbind(data.intent);
2029 try {
2030 if (doRebind) {
2031 ActivityManagerNative.getDefault().unbindFinished(
2032 data.token, data.intent, doRebind);
2033 } else {
2034 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002035 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
2037 } catch (RemoteException ex) {
2038 }
2039 } catch (Exception e) {
2040 if (!mInstrumentation.onException(s, e)) {
2041 throw new RuntimeException(
2042 "Unable to unbind to service " + s
2043 + " with " + data.intent + ": " + e.toString(), e);
2044 }
2045 }
2046 }
2047 }
2048
Dianne Hackborn625ac272010-09-17 18:29:22 -07002049 private void handleDumpService(DumpComponentInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002051 Service s = mServices.get(info.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 if (s != null) {
2053 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2054 s.dump(info.fd, pw, info.args);
2055 pw.close();
2056 }
2057 } finally {
2058 synchronized (info) {
2059 info.dumped = true;
2060 info.notifyAll();
2061 }
2062 }
2063 }
2064
Dianne Hackborn625ac272010-09-17 18:29:22 -07002065 private void handleDumpActivity(DumpComponentInfo info) {
2066 try {
2067 ActivityClientRecord r = mActivities.get(info.token);
2068 if (r != null && r.activity != null) {
2069 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2070 r.activity.dump(info.fd, pw, info.args);
2071 pw.close();
2072 }
2073 } finally {
2074 synchronized (info) {
2075 info.dumped = true;
2076 info.notifyAll();
2077 }
2078 }
2079 }
2080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 private final void handleServiceArgs(ServiceArgsData data) {
2082 Service s = mServices.get(data.token);
2083 if (s != null) {
2084 try {
2085 if (data.args != null) {
2086 data.args.setExtrasClassLoader(s.getClassLoader());
2087 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002088 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002089
2090 QueuedWork.waitToFinish();
2091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002093 ActivityManagerNative.getDefault().serviceDoneExecuting(
2094 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 } catch (RemoteException e) {
2096 // nothing to do.
2097 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002098 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 } catch (Exception e) {
2100 if (!mInstrumentation.onException(s, e)) {
2101 throw new RuntimeException(
2102 "Unable to start service " + s
2103 + " with " + data.args + ": " + e.toString(), e);
2104 }
2105 }
2106 }
2107 }
2108
2109 private final void handleStopService(IBinder token) {
2110 Service s = mServices.remove(token);
2111 if (s != null) {
2112 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002113 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 s.onDestroy();
2115 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002116 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002118 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002120
2121 QueuedWork.waitToFinish();
2122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002124 ActivityManagerNative.getDefault().serviceDoneExecuting(
2125 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 } catch (RemoteException e) {
2127 // nothing to do.
2128 }
2129 } catch (Exception e) {
2130 if (!mInstrumentation.onException(s, e)) {
2131 throw new RuntimeException(
2132 "Unable to stop service " + s
2133 + ": " + e.toString(), e);
2134 }
2135 }
2136 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002137 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 }
2139
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002140 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002142 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002143 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 + " finished=" + r.activity.mFinished);
2145 if (r != null && !r.activity.mFinished) {
2146 if (clearHide) {
2147 r.hideForNow = false;
2148 r.activity.mStartedActivity = false;
2149 }
2150 try {
2151 if (r.pendingIntents != null) {
2152 deliverNewIntents(r, r.pendingIntents);
2153 r.pendingIntents = null;
2154 }
2155 if (r.pendingResults != null) {
2156 deliverResults(r, r.pendingResults);
2157 r.pendingResults = null;
2158 }
2159 r.activity.performResume();
2160
Bob Leee5408332009-09-04 18:31:17 -07002161 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 r.paused = false;
2165 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 r.state = null;
2167 } catch (Exception e) {
2168 if (!mInstrumentation.onException(r.activity, e)) {
2169 throw new RuntimeException(
2170 "Unable to resume activity "
2171 + r.intent.getComponent().toShortString()
2172 + ": " + e.toString(), e);
2173 }
2174 }
2175 }
2176 return r;
2177 }
2178
2179 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2180 // If we are getting ready to gc after going to the background, well
2181 // we are back active so skip it.
2182 unscheduleGcIdler();
2183
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002184 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185
2186 if (r != null) {
2187 final Activity a = r.activity;
2188
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002189 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 TAG, "Resume " + r + " started activity: " +
2191 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2192 + ", finished: " + a.mFinished);
2193
2194 final int forwardBit = isForward ?
2195 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 // If the window hasn't yet been added to the window manager,
2198 // and this guy didn't finish itself or start another activity,
2199 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002200 boolean willBeVisible = !a.mStartedActivity;
2201 if (!willBeVisible) {
2202 try {
2203 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2204 a.getActivityToken());
2205 } catch (RemoteException e) {
2206 }
2207 }
2208 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 r.window = r.activity.getWindow();
2210 View decor = r.window.getDecorView();
2211 decor.setVisibility(View.INVISIBLE);
2212 ViewManager wm = a.getWindowManager();
2213 WindowManager.LayoutParams l = r.window.getAttributes();
2214 a.mDecor = decor;
2215 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2216 l.softInputMode |= forwardBit;
2217 if (a.mVisibleFromClient) {
2218 a.mWindowAdded = true;
2219 wm.addView(decor, l);
2220 }
2221
2222 // If the window has already been added, but during resume
2223 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002224 // window visible.
2225 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002226 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 TAG, "Launch " + r + " mStartedActivity set");
2228 r.hideForNow = true;
2229 }
2230
2231 // The window is now visible if it has been added, we are not
2232 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002233 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002234 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002236 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002237 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 performConfigurationChanged(r.activity, r.newConfig);
2239 r.newConfig = null;
2240 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002241 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 + isForward);
2243 WindowManager.LayoutParams l = r.window.getAttributes();
2244 if ((l.softInputMode
2245 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2246 != forwardBit) {
2247 l.softInputMode = (l.softInputMode
2248 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2249 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002250 if (r.activity.mVisibleFromClient) {
2251 ViewManager wm = a.getWindowManager();
2252 View decor = r.window.getDecorView();
2253 wm.updateViewLayout(decor, l);
2254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 }
2256 r.activity.mVisibleFromServer = true;
2257 mNumVisibleActivities++;
2258 if (r.activity.mVisibleFromClient) {
2259 r.activity.makeVisible();
2260 }
2261 }
2262
2263 r.nextIdle = mNewActivities;
2264 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002265 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 TAG, "Scheduling idle handler for " + r);
2267 Looper.myQueue().addIdleHandler(new Idler());
2268
2269 } else {
2270 // If an exception was thrown when trying to resume, then
2271 // just end this activity.
2272 try {
2273 ActivityManagerNative.getDefault()
2274 .finishActivity(token, Activity.RESULT_CANCELED, null);
2275 } catch (RemoteException ex) {
2276 }
2277 }
2278 }
2279
2280 private int mThumbnailWidth = -1;
2281 private int mThumbnailHeight = -1;
2282
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002283 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 Bitmap thumbnail = null;
2285 try {
2286 int w = mThumbnailWidth;
2287 int h;
2288 if (w < 0) {
2289 Resources res = r.activity.getResources();
2290 mThumbnailHeight = h =
2291 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2292
2293 mThumbnailWidth = w =
2294 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2295 } else {
2296 h = mThumbnailHeight;
2297 }
2298
Jim Miller0b2a6d02010-07-13 18:01:29 -07002299 // On platforms where we don't want thumbnails, set dims to (0,0)
2300 if ((w > 0) && (h > 0)) {
2301 View topView = r.activity.getWindow().getDecorView();
2302
2303 // Maximize bitmap by capturing in native aspect.
2304 if (topView.getWidth() >= topView.getHeight()) {
2305 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2306 } else {
2307 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2308 }
2309
2310 thumbnail.eraseColor(0);
2311 Canvas cv = new Canvas(thumbnail);
2312 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2313 thumbnail = null;
2314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 } catch (Exception e) {
2318 if (!mInstrumentation.onException(r.activity, e)) {
2319 throw new RuntimeException(
2320 "Unable to create thumbnail of "
2321 + r.intent.getComponent().toShortString()
2322 + ": " + e.toString(), e);
2323 }
2324 thumbnail = null;
2325 }
2326
2327 return thumbnail;
2328 }
2329
2330 private final void handlePauseActivity(IBinder token, boolean finished,
2331 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002332 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002334 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 if (userLeaving) {
2336 performUserLeavingActivity(r);
2337 }
Bob Leee5408332009-09-04 18:31:17 -07002338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 r.activity.mConfigChangeFlags |= configChanges;
2340 Bundle state = performPauseActivity(token, finished, true);
2341
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002342 // Make sure any pending writes are now committed.
2343 QueuedWork.waitToFinish();
2344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 // Tell the activity manager we have paused.
2346 try {
2347 ActivityManagerNative.getDefault().activityPaused(token, state);
2348 } catch (RemoteException ex) {
2349 }
2350 }
2351 }
2352
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002353 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 mInstrumentation.callActivityOnUserLeaving(r.activity);
2355 }
2356
2357 final Bundle performPauseActivity(IBinder token, boolean finished,
2358 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002359 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 return r != null ? performPauseActivity(r, finished, saveState) : null;
2361 }
2362
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002363 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 boolean saveState) {
2365 if (r.paused) {
2366 if (r.activity.mFinished) {
2367 // If we are finishing, we won't call onResume() in certain cases.
2368 // So here we likewise don't want to call onPause() if the activity
2369 // isn't resumed.
2370 return null;
2371 }
2372 RuntimeException e = new RuntimeException(
2373 "Performing pause of activity that is not resumed: "
2374 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002375 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 }
2377 Bundle state = null;
2378 if (finished) {
2379 r.activity.mFinished = true;
2380 }
2381 try {
2382 // Next have the activity save its current state and managed dialogs...
2383 if (!r.activity.mFinished && saveState) {
2384 state = new Bundle();
2385 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2386 r.state = state;
2387 }
2388 // Now we are idle.
2389 r.activity.mCalled = false;
2390 mInstrumentation.callActivityOnPause(r.activity);
2391 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2392 if (!r.activity.mCalled) {
2393 throw new SuperNotCalledException(
2394 "Activity " + r.intent.getComponent().toShortString() +
2395 " did not call through to super.onPause()");
2396 }
2397
2398 } catch (SuperNotCalledException e) {
2399 throw e;
2400
2401 } catch (Exception e) {
2402 if (!mInstrumentation.onException(r.activity, e)) {
2403 throw new RuntimeException(
2404 "Unable to pause activity "
2405 + r.intent.getComponent().toShortString()
2406 + ": " + e.toString(), e);
2407 }
2408 }
2409 r.paused = true;
2410 return state;
2411 }
2412
2413 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002414 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 performStopActivityInner(r, null, false);
2416 }
2417
2418 private static class StopInfo {
2419 Bitmap thumbnail;
2420 CharSequence description;
2421 }
2422
2423 private final class ProviderRefCount {
2424 public int count;
2425 ProviderRefCount(int pCount) {
2426 count = pCount;
2427 }
2428 }
2429
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002430 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002432 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 if (r != null) {
2434 if (!keepShown && r.stopped) {
2435 if (r.activity.mFinished) {
2436 // If we are finishing, we won't call onResume() in certain
2437 // cases. So here we likewise don't want to call onStop()
2438 // if the activity isn't resumed.
2439 return;
2440 }
2441 RuntimeException e = new RuntimeException(
2442 "Performing stop of activity that is not resumed: "
2443 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002444 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 }
2446
2447 if (info != null) {
2448 try {
2449 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002450 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 info.description = r.activity.onCreateDescription();
2452 } catch (Exception e) {
2453 if (!mInstrumentation.onException(r.activity, e)) {
2454 throw new RuntimeException(
2455 "Unable to save state of activity "
2456 + r.intent.getComponent().toShortString()
2457 + ": " + e.toString(), e);
2458 }
2459 }
2460 }
2461
2462 if (!keepShown) {
2463 try {
2464 // Now we are idle.
2465 r.activity.performStop();
2466 } catch (Exception e) {
2467 if (!mInstrumentation.onException(r.activity, e)) {
2468 throw new RuntimeException(
2469 "Unable to stop activity "
2470 + r.intent.getComponent().toShortString()
2471 + ": " + e.toString(), e);
2472 }
2473 }
2474 r.stopped = true;
2475 }
2476
2477 r.paused = true;
2478 }
2479 }
2480
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002481 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 View v = r.activity.mDecor;
2483 if (v != null) {
2484 if (show) {
2485 if (!r.activity.mVisibleFromServer) {
2486 r.activity.mVisibleFromServer = true;
2487 mNumVisibleActivities++;
2488 if (r.activity.mVisibleFromClient) {
2489 r.activity.makeVisible();
2490 }
2491 }
2492 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002493 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002494 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 performConfigurationChanged(r.activity, r.newConfig);
2496 r.newConfig = null;
2497 }
2498 } else {
2499 if (r.activity.mVisibleFromServer) {
2500 r.activity.mVisibleFromServer = false;
2501 mNumVisibleActivities--;
2502 v.setVisibility(View.INVISIBLE);
2503 }
2504 }
2505 }
2506 }
2507
2508 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002509 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 r.activity.mConfigChangeFlags |= configChanges;
2511
2512 StopInfo info = new StopInfo();
2513 performStopActivityInner(r, info, show);
2514
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002515 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 TAG, "Finishing stop of " + r + ": show=" + show
2517 + " win=" + r.window);
2518
2519 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 // Tell activity manager we have been stopped.
2522 try {
2523 ActivityManagerNative.getDefault().activityStopped(
2524 r.token, info.thumbnail, info.description);
2525 } catch (RemoteException ex) {
2526 }
2527 }
2528
2529 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002530 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 if (r.stopped) {
2532 r.activity.performRestart();
2533 r.stopped = false;
2534 }
2535 }
2536
2537 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002538 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 if (!show && !r.stopped) {
2540 performStopActivityInner(r, null, show);
2541 } else if (show && r.stopped) {
2542 // If we are getting ready to gc after going to the background, well
2543 // we are back active so skip it.
2544 unscheduleGcIdler();
2545
2546 r.activity.performRestart();
2547 r.stopped = false;
2548 }
2549 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002550 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 TAG, "Handle window " + r + " visibility: " + show);
2552 updateVisibility(r, show);
2553 }
2554 }
2555
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002556 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 final int N = results.size();
2558 for (int i=0; i<N; i++) {
2559 ResultInfo ri = results.get(i);
2560 try {
2561 if (ri.mData != null) {
2562 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2563 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002564 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002565 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 r.activity.dispatchActivityResult(ri.mResultWho,
2567 ri.mRequestCode, ri.mResultCode, ri.mData);
2568 } catch (Exception e) {
2569 if (!mInstrumentation.onException(r.activity, e)) {
2570 throw new RuntimeException(
2571 "Failure delivering result " + ri + " to activity "
2572 + r.intent.getComponent().toShortString()
2573 + ": " + e.toString(), e);
2574 }
2575 }
2576 }
2577 }
2578
2579 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002580 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002581 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 if (r != null) {
2583 final boolean resumed = !r.paused;
2584 if (!r.activity.mFinished && r.activity.mDecor != null
2585 && r.hideForNow && resumed) {
2586 // We had hidden the activity because it started another
2587 // one... we have gotten a result back and we are not
2588 // paused, so make sure our window is visible.
2589 updateVisibility(r, true);
2590 }
2591 if (resumed) {
2592 try {
2593 // Now we are idle.
2594 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002595 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 mInstrumentation.callActivityOnPause(r.activity);
2597 if (!r.activity.mCalled) {
2598 throw new SuperNotCalledException(
2599 "Activity " + r.intent.getComponent().toShortString()
2600 + " did not call through to super.onPause()");
2601 }
2602 } catch (SuperNotCalledException e) {
2603 throw e;
2604 } catch (Exception e) {
2605 if (!mInstrumentation.onException(r.activity, e)) {
2606 throw new RuntimeException(
2607 "Unable to pause activity "
2608 + r.intent.getComponent().toShortString()
2609 + ": " + e.toString(), e);
2610 }
2611 }
2612 }
2613 deliverResults(r, res.results);
2614 if (resumed) {
2615 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002616 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 }
2618 }
2619 }
2620
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002621 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 return performDestroyActivity(token, finishing, 0, false);
2623 }
2624
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002625 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002627 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002628 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 if (r != null) {
2630 r.activity.mConfigChangeFlags |= configChanges;
2631 if (finishing) {
2632 r.activity.mFinished = true;
2633 }
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05002634 if (getNonConfigInstance) {
2635 r.activity.mChangingConfigurations = true;
2636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 if (!r.paused) {
2638 try {
2639 r.activity.mCalled = false;
2640 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002641 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 r.activity.getComponentName().getClassName());
2643 if (!r.activity.mCalled) {
2644 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002645 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 + " did not call through to super.onPause()");
2647 }
2648 } catch (SuperNotCalledException e) {
2649 throw e;
2650 } catch (Exception e) {
2651 if (!mInstrumentation.onException(r.activity, e)) {
2652 throw new RuntimeException(
2653 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002654 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 + ": " + e.toString(), e);
2656 }
2657 }
2658 r.paused = true;
2659 }
2660 if (!r.stopped) {
2661 try {
2662 r.activity.performStop();
2663 } catch (SuperNotCalledException e) {
2664 throw e;
2665 } catch (Exception e) {
2666 if (!mInstrumentation.onException(r.activity, e)) {
2667 throw new RuntimeException(
2668 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002669 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 + ": " + e.toString(), e);
2671 }
2672 }
2673 r.stopped = true;
2674 }
2675 if (getNonConfigInstance) {
2676 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002677 r.lastNonConfigurationInstances
2678 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 } catch (Exception e) {
2680 if (!mInstrumentation.onException(r.activity, e)) {
2681 throw new RuntimeException(
2682 "Unable to retain activity "
2683 + r.intent.getComponent().toShortString()
2684 + ": " + e.toString(), e);
2685 }
2686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 }
2688 try {
2689 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002690 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 if (!r.activity.mCalled) {
2692 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002693 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 " did not call through to super.onDestroy()");
2695 }
2696 if (r.window != null) {
2697 r.window.closeAllPanels();
2698 }
2699 } catch (SuperNotCalledException e) {
2700 throw e;
2701 } catch (Exception e) {
2702 if (!mInstrumentation.onException(r.activity, e)) {
2703 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002704 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2705 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 }
2707 }
2708 }
2709 mActivities.remove(token);
2710
2711 return r;
2712 }
2713
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002714 private static String safeToComponentShortString(Intent intent) {
2715 ComponentName component = intent.getComponent();
2716 return component == null ? "[Unknown]" : component.toShortString();
2717 }
2718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 private final void handleDestroyActivity(IBinder token, boolean finishing,
2720 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002721 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 configChanges, getNonConfigInstance);
2723 if (r != null) {
2724 WindowManager wm = r.activity.getWindowManager();
2725 View v = r.activity.mDecor;
2726 if (v != null) {
2727 if (r.activity.mVisibleFromServer) {
2728 mNumVisibleActivities--;
2729 }
2730 IBinder wtoken = v.getWindowToken();
2731 if (r.activity.mWindowAdded) {
2732 wm.removeViewImmediate(v);
2733 }
2734 if (wtoken != null) {
2735 WindowManagerImpl.getDefault().closeAll(wtoken,
2736 r.activity.getClass().getName(), "Activity");
2737 }
2738 r.activity.mDecor = null;
2739 }
2740 WindowManagerImpl.getDefault().closeAll(token,
2741 r.activity.getClass().getName(), "Activity");
2742
2743 // Mocked out contexts won't be participating in the normal
2744 // process lifecycle, but if we're running with a proper
2745 // ApplicationContext we need to have it tear down things
2746 // cleanly.
2747 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002748 if (c instanceof ContextImpl) {
2749 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 r.activity.getClass().getName(), "Activity");
2751 }
2752 }
2753 if (finishing) {
2754 try {
2755 ActivityManagerNative.getDefault().activityDestroyed(token);
2756 } catch (RemoteException ex) {
2757 // If the system process has died, it's game over for everyone.
2758 }
2759 }
2760 }
2761
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002762 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 // If we are getting ready to gc after going to the background, well
2764 // we are back active so skip it.
2765 unscheduleGcIdler();
2766
2767 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002768
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002769 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002770 + tmp.token + " with configChanges=0x"
2771 + Integer.toHexString(configChanges));
2772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 // First: make sure we have the most recent configuration and most
2774 // recent version of the activity, or skip it if some previous call
2775 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002776 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 int N = mRelaunchingActivities.size();
2778 IBinder token = tmp.token;
2779 tmp = null;
2780 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002781 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 if (r.token == token) {
2783 tmp = r;
2784 mRelaunchingActivities.remove(i);
2785 i--;
2786 N--;
2787 }
2788 }
Bob Leee5408332009-09-04 18:31:17 -07002789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002791 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 return;
2793 }
Bob Leee5408332009-09-04 18:31:17 -07002794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 if (mPendingConfiguration != null) {
2796 changedConfig = mPendingConfiguration;
2797 mPendingConfiguration = null;
2798 }
2799 }
Bob Leee5408332009-09-04 18:31:17 -07002800
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002801 if (tmp.createdConfig != null) {
2802 // If the activity manager is passing us its current config,
2803 // assume that is really what we want regardless of what we
2804 // may have pending.
2805 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002806 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2807 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2808 if (changedConfig == null
2809 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2810 changedConfig = tmp.createdConfig;
2811 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002812 }
2813 }
2814
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002815 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002816 + tmp.token + ": changedConfig=" + changedConfig);
2817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 // If there was a pending configuration change, execute it first.
2819 if (changedConfig != null) {
2820 handleConfigurationChanged(changedConfig);
2821 }
Bob Leee5408332009-09-04 18:31:17 -07002822
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002823 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002824 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 if (r == null) {
2826 return;
2827 }
Bob Leee5408332009-09-04 18:31:17 -07002828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002830 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 Bundle savedState = null;
2833 if (!r.paused) {
2834 savedState = performPauseActivity(r.token, false, true);
2835 }
Bob Leee5408332009-09-04 18:31:17 -07002836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 r.activity = null;
2840 r.window = null;
2841 r.hideForNow = false;
2842 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002843 // Merge any pending results and pending intents; don't just replace them
2844 if (tmp.pendingResults != null) {
2845 if (r.pendingResults == null) {
2846 r.pendingResults = tmp.pendingResults;
2847 } else {
2848 r.pendingResults.addAll(tmp.pendingResults);
2849 }
2850 }
2851 if (tmp.pendingIntents != null) {
2852 if (r.pendingIntents == null) {
2853 r.pendingIntents = tmp.pendingIntents;
2854 } else {
2855 r.pendingIntents.addAll(tmp.pendingIntents);
2856 }
2857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 r.startsNotResumed = tmp.startsNotResumed;
2859 if (savedState != null) {
2860 r.state = savedState;
2861 }
Bob Leee5408332009-09-04 18:31:17 -07002862
Christopher Tateb70f3df2009-04-07 16:07:59 -07002863 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 }
2865
2866 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002867 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 Bitmap thumbnail = createThumbnailBitmap(r);
2869 CharSequence description = null;
2870 try {
2871 description = r.activity.onCreateDescription();
2872 } catch (Exception e) {
2873 if (!mInstrumentation.onException(r.activity, e)) {
2874 throw new RuntimeException(
2875 "Unable to create description of activity "
2876 + r.intent.getComponent().toShortString()
2877 + ": " + e.toString(), e);
2878 }
2879 }
2880 //System.out.println("Reporting top thumbnail " + thumbnail);
2881 try {
2882 ActivityManagerNative.getDefault().reportThumbnail(
2883 token, thumbnail, description);
2884 } catch (RemoteException ex) {
2885 }
2886 }
2887
2888 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2889 boolean allActivities, Configuration newConfig) {
2890 ArrayList<ComponentCallbacks> callbacks
2891 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002894 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002896 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 Activity a = ar.activity;
2898 if (a != null) {
2899 if (!ar.activity.mFinished && (allActivities ||
2900 (a != null && !ar.paused))) {
2901 // If the activity is currently resumed, its configuration
2902 // needs to change right now.
2903 callbacks.add(a);
2904 } else if (newConfig != null) {
2905 // Otherwise, we will tell it about the change
2906 // the next time it is resumed or shown. Note that
2907 // the activity manager may, before then, decide the
2908 // activity needs to be destroyed to handle its new
2909 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002910 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002911 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 ar.newConfig = newConfig;
2913 }
2914 }
2915 }
2916 }
2917 if (mServices.size() > 0) {
2918 Iterator<Service> it = mServices.values().iterator();
2919 while (it.hasNext()) {
2920 callbacks.add(it.next());
2921 }
2922 }
2923 synchronized (mProviderMap) {
2924 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002925 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 while (it.hasNext()) {
2927 callbacks.add(it.next().mLocalProvider);
2928 }
2929 }
2930 }
2931 final int N = mAllApplications.size();
2932 for (int i=0; i<N; i++) {
2933 callbacks.add(mAllApplications.get(i));
2934 }
Bob Leee5408332009-09-04 18:31:17 -07002935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 return callbacks;
2937 }
Bob Leee5408332009-09-04 18:31:17 -07002938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 private final void performConfigurationChanged(
2940 ComponentCallbacks cb, Configuration config) {
2941 // Only for Activity objects, check that they actually call up to their
2942 // superclass implementation. ComponentCallbacks is an interface, so
2943 // we check the runtime type and act accordingly.
2944 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2945 if (activity != null) {
2946 activity.mCalled = false;
2947 }
Bob Leee5408332009-09-04 18:31:17 -07002948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 boolean shouldChangeConfig = false;
2950 if ((activity == null) || (activity.mCurrentConfig == null)) {
2951 shouldChangeConfig = true;
2952 } else {
Bob Leee5408332009-09-04 18:31:17 -07002953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 // If the new config is the same as the config this Activity
2955 // is already running with then don't bother calling
2956 // onConfigurationChanged
2957 int diff = activity.mCurrentConfig.diff(config);
2958 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 // If this activity doesn't handle any of the config changes
2961 // then don't bother calling onConfigurationChanged as we're
2962 // going to destroy it.
2963 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2964 shouldChangeConfig = true;
2965 }
2966 }
2967 }
Bob Leee5408332009-09-04 18:31:17 -07002968
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002969 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002970 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 if (shouldChangeConfig) {
2972 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 if (activity != null) {
2975 if (!activity.mCalled) {
2976 throw new SuperNotCalledException(
2977 "Activity " + activity.getLocalClassName() +
2978 " did not call through to super.onConfigurationChanged()");
2979 }
2980 activity.mConfigChangeFlags = 0;
2981 activity.mCurrentConfig = new Configuration(config);
2982 }
2983 }
2984 }
2985
Dianne Hackbornae078162010-03-18 11:29:37 -07002986 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002987 if (mResConfiguration == null) {
2988 mResConfiguration = new Configuration();
2989 }
2990 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002991 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002992 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002993 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002994 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002995 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002996 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002997
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002998 // set it for java, this also affects newly created Resources
2999 if (config.locale != null) {
3000 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 }
Bob Leee5408332009-09-04 18:31:17 -07003002
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003003 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07003004
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003005 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003006 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003007
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003008 Iterator<WeakReference<Resources>> it =
3009 mActiveResources.values().iterator();
3010 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3011 // mActiveResources.entrySet().iterator();
3012 while (it.hasNext()) {
3013 WeakReference<Resources> v = it.next();
3014 Resources r = v.get();
3015 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003016 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003017 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003018 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003019 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003020 // + " " + r + ": " + r.getConfiguration());
3021 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003022 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003023 it.remove();
3024 }
3025 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003026
3027 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003028 }
3029
3030 final void handleConfigurationChanged(Configuration config) {
3031
3032 ArrayList<ComponentCallbacks> callbacks = null;
3033
3034 synchronized (mPackages) {
3035 if (mPendingConfiguration != null) {
3036 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3037 config = mPendingConfiguration;
3038 }
3039 mPendingConfiguration = null;
3040 }
3041
3042 if (config == null) {
3043 return;
3044 }
3045
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003046 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003047 + config);
3048
3049 applyConfigurationToResourcesLocked(config);
3050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 if (mConfiguration == null) {
3052 mConfiguration = new Configuration();
3053 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003054 if (!mConfiguration.isOtherSeqNewer(config)) {
3055 return;
3056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 callbacks = collectComponentCallbacksLocked(false, config);
3060 }
Bob Leee5408332009-09-04 18:31:17 -07003061
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003062 if (callbacks != null) {
3063 final int N = callbacks.size();
3064 for (int i=0; i<N; i++) {
3065 performConfigurationChanged(callbacks.get(i), config);
3066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 }
3068 }
3069
3070 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003071 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 if (r == null || r.activity == null) {
3073 return;
3074 }
Bob Leee5408332009-09-04 18:31:17 -07003075
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003076 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003077 + r.activityInfo.name);
3078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 performConfigurationChanged(r.activity, mConfiguration);
3080 }
3081
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003082 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003083 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003084 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003085 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3086 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003087 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003088 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003089 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003090 } finally {
3091 try {
3092 pcd.fd.close();
3093 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003094 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003095 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003096 }
3097 } else {
3098 Debug.stopMethodTracing();
3099 }
3100 }
Bob Leee5408332009-09-04 18:31:17 -07003101
Andy McFadden824c5102010-07-09 16:26:57 -07003102 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3103 if (managed) {
3104 try {
3105 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3106 } catch (IOException e) {
3107 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3108 + " -- can the process access this path?");
3109 } finally {
3110 try {
3111 dhd.fd.close();
3112 } catch (IOException e) {
3113 Slog.w(TAG, "Failure closing profile fd", e);
3114 }
3115 }
3116 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003117 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003118 }
3119 }
3120
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003121 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3122 boolean hasPkgInfo = false;
3123 if (packages != null) {
3124 for (int i=packages.length-1; i>=0; i--) {
3125 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3126 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003127 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003128 ref = mPackages.get(packages[i]);
3129 if (ref != null && ref.get() != null) {
3130 hasPkgInfo = true;
3131 } else {
3132 ref = mResourcePackages.get(packages[i]);
3133 if (ref != null && ref.get() != null) {
3134 hasPkgInfo = true;
3135 }
3136 }
3137 }
3138 mPackages.remove(packages[i]);
3139 mResourcePackages.remove(packages[i]);
3140 }
3141 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003142 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003143 hasPkgInfo);
3144 }
3145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 final void handleLowMemory() {
3147 ArrayList<ComponentCallbacks> callbacks
3148 = new ArrayList<ComponentCallbacks>();
3149
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003150 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 callbacks = collectComponentCallbacksLocked(true, null);
3152 }
Bob Leee5408332009-09-04 18:31:17 -07003153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 final int N = callbacks.size();
3155 for (int i=0; i<N; i++) {
3156 callbacks.get(i).onLowMemory();
3157 }
3158
Chris Tatece229052009-03-25 16:44:52 -07003159 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3160 if (Process.myUid() != Process.SYSTEM_UID) {
3161 int sqliteReleased = SQLiteDatabase.releaseMemory();
3162 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3163 }
Bob Leee5408332009-09-04 18:31:17 -07003164
Mike Reedcaf0df12009-04-27 14:32:05 -04003165 // Ask graphics to free up as much as possible (font/image caches)
3166 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167
3168 BinderInternal.forceGc("mem");
3169 }
3170
3171 private final void handleBindApplication(AppBindData data) {
3172 mBoundApplication = data;
3173 mConfiguration = new Configuration(data.config);
3174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003176 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 android.ddm.DdmHandleAppName.setAppName(data.processName);
3178
3179 /*
3180 * Before spawning a new process, reset the time zone to be the system time zone.
3181 * This needs to be done because the system time zone could have changed after the
3182 * the spawning of this process. Without doing this this process would have the incorrect
3183 * system time zone.
3184 */
3185 TimeZone.setDefault(null);
3186
3187 /*
3188 * Initialize the default locale in this process for the reasons we set the time zone.
3189 */
3190 Locale.setDefault(data.config.locale);
3191
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003192 /*
3193 * Update the system configuration since its preloaded and might not
3194 * reflect configuration changes. The configuration object passed
3195 * in AppBindData can be safely assumed to be up to date
3196 */
3197 Resources.getSystem().updateConfiguration(mConfiguration, null);
3198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 data.info = getPackageInfoNoCheck(data.appInfo);
3200
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003201 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003202 * For system applications on userdebug/eng builds, log stack
3203 * traces of disk and network access to dropbox for analysis.
3204 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003205 if ((data.appInfo.flags &
3206 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003207 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3208 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003209 }
3210
3211 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003212 * For apps targetting SDK Honeycomb or later, we don't allow
3213 * network usage on the main event loop / UI thread.
3214 *
3215 * Note to those grepping: this is what ultimately throws
3216 * NetworkOnMainThreadException ...
3217 */
3218 if (data.appInfo.targetSdkVersion > 9) {
3219 StrictMode.enableDeathOnNetwork();
3220 }
3221
3222 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003223 * Switch this process to density compatibility mode if needed.
3224 */
3225 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3226 == 0) {
3227 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3228 }
Bob Leee5408332009-09-04 18:31:17 -07003229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3231 // XXX should have option to change the port.
3232 Debug.changeDebugPort(8100);
3233 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003234 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 + " is waiting for the debugger on port 8100...");
3236
3237 IActivityManager mgr = ActivityManagerNative.getDefault();
3238 try {
3239 mgr.showWaitingForDebugger(mAppThread, true);
3240 } catch (RemoteException ex) {
3241 }
3242
3243 Debug.waitForDebugger();
3244
3245 try {
3246 mgr.showWaitingForDebugger(mAppThread, false);
3247 } catch (RemoteException ex) {
3248 }
3249
3250 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003251 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 + " can be debugged on port 8100...");
3253 }
3254 }
3255
3256 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003257 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 appContext.init(data.info, null, this);
3259 InstrumentationInfo ii = null;
3260 try {
3261 ii = appContext.getPackageManager().
3262 getInstrumentationInfo(data.instrumentationName, 0);
3263 } catch (PackageManager.NameNotFoundException e) {
3264 }
3265 if (ii == null) {
3266 throw new RuntimeException(
3267 "Unable to find instrumentation info for: "
3268 + data.instrumentationName);
3269 }
3270
3271 mInstrumentationAppDir = ii.sourceDir;
3272 mInstrumentationAppPackage = ii.packageName;
3273 mInstrumentedAppDir = data.info.getAppDir();
3274
3275 ApplicationInfo instrApp = new ApplicationInfo();
3276 instrApp.packageName = ii.packageName;
3277 instrApp.sourceDir = ii.sourceDir;
3278 instrApp.publicSourceDir = ii.publicSourceDir;
3279 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003280 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003281 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003283 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 instrContext.init(pi, null, this);
3285
3286 try {
3287 java.lang.ClassLoader cl = instrContext.getClassLoader();
3288 mInstrumentation = (Instrumentation)
3289 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3290 } catch (Exception e) {
3291 throw new RuntimeException(
3292 "Unable to instantiate instrumentation "
3293 + data.instrumentationName + ": " + e.toString(), e);
3294 }
3295
3296 mInstrumentation.init(this, instrContext, appContext,
3297 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3298
3299 if (data.profileFile != null && !ii.handleProfiling) {
3300 data.handlingProfiling = true;
3301 File file = new File(data.profileFile);
3302 file.getParentFile().mkdirs();
3303 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3304 }
3305
3306 try {
3307 mInstrumentation.onCreate(data.instrumentationArgs);
3308 }
3309 catch (Exception e) {
3310 throw new RuntimeException(
3311 "Exception thrown in onCreate() of "
3312 + data.instrumentationName + ": " + e.toString(), e);
3313 }
3314
3315 } else {
3316 mInstrumentation = new Instrumentation();
3317 }
3318
Christopher Tate181fafa2009-05-14 11:12:14 -07003319 // If the app is being launched for full backup or restore, bring it up in
3320 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003321 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 mInitialApplication = app;
3323
3324 List<ProviderInfo> providers = data.providers;
3325 if (providers != null) {
3326 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003327 // For process that contain content providers, we want to
3328 // ensure that the JIT is enabled "at some point".
3329 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 }
3331
3332 try {
3333 mInstrumentation.callApplicationOnCreate(app);
3334 } catch (Exception e) {
3335 if (!mInstrumentation.onException(app, e)) {
3336 throw new RuntimeException(
3337 "Unable to create application " + app.getClass().getName()
3338 + ": " + e.toString(), e);
3339 }
3340 }
3341 }
3342
3343 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3344 IActivityManager am = ActivityManagerNative.getDefault();
3345 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3346 Debug.stopMethodTracing();
3347 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003348 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 // + ", app thr: " + mAppThread);
3350 try {
3351 am.finishInstrumentation(mAppThread, resultCode, results);
3352 } catch (RemoteException ex) {
3353 }
3354 }
3355
3356 private final void installContentProviders(
3357 Context context, List<ProviderInfo> providers) {
3358 final ArrayList<IActivityManager.ContentProviderHolder> results =
3359 new ArrayList<IActivityManager.ContentProviderHolder>();
3360
3361 Iterator<ProviderInfo> i = providers.iterator();
3362 while (i.hasNext()) {
3363 ProviderInfo cpi = i.next();
3364 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003365 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 buf.append(cpi.authority);
3367 buf.append(": ");
3368 buf.append(cpi.name);
3369 Log.i(TAG, buf.toString());
3370 IContentProvider cp = installProvider(context, null, cpi, false);
3371 if (cp != null) {
3372 IActivityManager.ContentProviderHolder cph =
3373 new IActivityManager.ContentProviderHolder(cpi);
3374 cph.provider = cp;
3375 results.add(cph);
3376 // Don't ever unload this provider from the process.
3377 synchronized(mProviderMap) {
3378 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3379 }
3380 }
3381 }
3382
3383 try {
3384 ActivityManagerNative.getDefault().publishContentProviders(
3385 getApplicationThread(), results);
3386 } catch (RemoteException ex) {
3387 }
3388 }
3389
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003390 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003392 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 if (pr != null) {
3394 return pr.mProvider;
3395 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003396 return null;
3397 }
3398 }
3399
3400 private final IContentProvider getProvider(Context context, String name) {
3401 IContentProvider existing = getExistingProvider(context, name);
3402 if (existing != null) {
3403 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 }
3405
3406 IActivityManager.ContentProviderHolder holder = null;
3407 try {
3408 holder = ActivityManagerNative.getDefault().getContentProvider(
3409 getApplicationThread(), name);
3410 } catch (RemoteException ex) {
3411 }
3412 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003413 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 return null;
3415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416
3417 IContentProvider prov = installProvider(context, holder.provider,
3418 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003419 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 if (holder.noReleaseNeeded || holder.provider == null) {
3421 // We are not going to release the provider if it is an external
3422 // provider that doesn't care about being released, or if it is
3423 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003424 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 synchronized(mProviderMap) {
3426 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3427 }
3428 }
3429 return prov;
3430 }
3431
3432 public final IContentProvider acquireProvider(Context c, String name) {
3433 IContentProvider provider = getProvider(c, name);
3434 if(provider == null)
3435 return null;
3436 IBinder jBinder = provider.asBinder();
3437 synchronized(mProviderMap) {
3438 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3439 if(prc == null) {
3440 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3441 } else {
3442 prc.count++;
3443 } //end else
3444 } //end synchronized
3445 return provider;
3446 }
3447
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003448 public final IContentProvider acquireExistingProvider(Context c, String name) {
3449 IContentProvider provider = getExistingProvider(c, name);
3450 if(provider == null)
3451 return null;
3452 IBinder jBinder = provider.asBinder();
3453 synchronized(mProviderMap) {
3454 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3455 if(prc == null) {
3456 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3457 } else {
3458 prc.count++;
3459 } //end else
3460 } //end synchronized
3461 return provider;
3462 }
3463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003464 public final boolean releaseProvider(IContentProvider provider) {
3465 if(provider == null) {
3466 return false;
3467 }
3468 IBinder jBinder = provider.asBinder();
3469 synchronized(mProviderMap) {
3470 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3471 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003472 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 return false;
3474 } else {
3475 prc.count--;
3476 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003477 // Schedule the actual remove asynchronously, since we
3478 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003479 // TODO: it would be nice to post a delayed message, so
3480 // if we come back and need the same provider quickly
3481 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003482 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3483 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 } //end if
3485 } //end else
3486 } //end synchronized
3487 return true;
3488 }
3489
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003490 final void completeRemoveProvider(IContentProvider provider) {
3491 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003492 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003493 synchronized(mProviderMap) {
3494 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3495 if(prc != null && prc.count == 0) {
3496 mProviderRefCountMap.remove(jBinder);
3497 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003498 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003499 }
3500 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003501
3502 if (name != null) {
3503 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003504 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003505 "ActivityManagerNative.removeContentProvider(" + name);
3506 ActivityManagerNative.getDefault().removeContentProvider(
3507 getApplicationThread(), name);
3508 } catch (RemoteException e) {
3509 //do nothing content provider object is dead any way
3510 } //end catch
3511 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003512 }
3513
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003514 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003516 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 }
3518 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003520 String name = null;
3521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003523 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003525 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 IBinder myBinder = pr.mProvider.asBinder();
3527 if (myBinder == providerBinder) {
3528 //find if its published by this process itself
3529 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003530 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003531 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003533 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 "death recipient");
3535 //content provider is in another process
3536 myBinder.unlinkToDeath(pr, 0);
3537 iter.remove();
3538 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003539 if(name == null) {
3540 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 }
3542 } //end if myBinder
3543 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003544
3545 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 }
3547
3548 final void removeDeadProvider(String name, IContentProvider provider) {
3549 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003550 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003552 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003553 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003554 if (removed != null) {
3555 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 }
3558 }
3559 }
3560
3561 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003562 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003564 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003565 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003566 if (removed != null) {
3567 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 }
3570 }
3571
3572 private final IContentProvider installProvider(Context context,
3573 IContentProvider provider, ProviderInfo info, boolean noisy) {
3574 ContentProvider localProvider = null;
3575 if (provider == null) {
3576 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003577 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 + info.name);
3579 }
3580 Context c = null;
3581 ApplicationInfo ai = info.applicationInfo;
3582 if (context.getPackageName().equals(ai.packageName)) {
3583 c = context;
3584 } else if (mInitialApplication != null &&
3585 mInitialApplication.getPackageName().equals(ai.packageName)) {
3586 c = mInitialApplication;
3587 } else {
3588 try {
3589 c = context.createPackageContext(ai.packageName,
3590 Context.CONTEXT_INCLUDE_CODE);
3591 } catch (PackageManager.NameNotFoundException e) {
3592 }
3593 }
3594 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003595 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 ai.packageName +
3597 " while loading content provider " +
3598 info.name);
3599 return null;
3600 }
3601 try {
3602 final java.lang.ClassLoader cl = c.getClassLoader();
3603 localProvider = (ContentProvider)cl.
3604 loadClass(info.name).newInstance();
3605 provider = localProvider.getIContentProvider();
3606 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003607 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608 info.name + " from sourceDir " +
3609 info.applicationInfo.sourceDir);
3610 return null;
3611 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003612 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 TAG, "Instantiating local provider " + info.name);
3614 // XXX Need to create the correct context for this provider.
3615 localProvider.attachInfo(c, info);
3616 } catch (java.lang.Exception e) {
3617 if (!mInstrumentation.onException(null, e)) {
3618 throw new RuntimeException(
3619 "Unable to get provider " + info.name
3620 + ": " + e.toString(), e);
3621 }
3622 return null;
3623 }
3624 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003625 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 + info.name);
3627 }
3628
3629 synchronized (mProviderMap) {
3630 // Cache the pointer for the remote provider.
3631 String names[] = PATTERN_SEMICOLON.split(info.authority);
3632 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003633 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 localProvider);
3635 try {
3636 provider.asBinder().linkToDeath(pr, 0);
3637 mProviderMap.put(names[i], pr);
3638 } catch (RemoteException e) {
3639 return null;
3640 }
3641 }
3642 if (localProvider != null) {
3643 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003644 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 }
3646 }
3647
3648 return provider;
3649 }
3650
3651 private final void attach(boolean system) {
3652 sThreadLocal.set(this);
3653 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003655 ViewRoot.addFirstDrawHandler(new Runnable() {
3656 public void run() {
3657 ensureJitEnabled();
3658 }
3659 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3661 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3662 IActivityManager mgr = ActivityManagerNative.getDefault();
3663 try {
3664 mgr.attachApplication(mAppThread);
3665 } catch (RemoteException ex) {
3666 }
3667 } else {
3668 // Don't set application object here -- if the system crashes,
3669 // we can't display an alert, we just want to die die die.
3670 android.ddm.DdmHandleAppName.setAppName("system_process");
3671 try {
3672 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003673 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 context.init(getSystemContext().mPackageInfo, null, this);
3675 Application app = Instrumentation.newApplication(Application.class, context);
3676 mAllApplications.add(app);
3677 mInitialApplication = app;
3678 app.onCreate();
3679 } catch (Exception e) {
3680 throw new RuntimeException(
3681 "Unable to instantiate Application():" + e.toString(), e);
3682 }
3683 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003684
3685 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3686 public void onConfigurationChanged(Configuration newConfig) {
3687 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003688 // We need to apply this change to the resources
3689 // immediately, because upon returning the view
3690 // hierarchy will be informed about it.
3691 if (applyConfigurationToResourcesLocked(newConfig)) {
3692 // This actually changed the resources! Tell
3693 // everyone about it.
3694 if (mPendingConfiguration == null ||
3695 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3696 mPendingConfiguration = newConfig;
3697
3698 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3699 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003700 }
3701 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003702 }
3703 public void onLowMemory() {
3704 }
3705 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706 }
3707
3708 private final void detach()
3709 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 sThreadLocal.set(null);
3711 }
3712
3713 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003714 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 ActivityThread thread = new ActivityThread();
3716 thread.attach(true);
3717 return thread;
3718 }
3719
3720 public final void installSystemProviders(List providers) {
3721 if (providers != null) {
3722 installContentProviders(mInitialApplication,
3723 (List<ProviderInfo>)providers);
3724 }
3725 }
3726
3727 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003728 SamplingProfilerIntegration.start();
3729
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08003730 // CloseGuard defaults to true and can be quite spammy. We
3731 // disable it here, but selectively enable it later (via
3732 // StrictMode) on debug builds, but using DropBox, not logs.
3733 CloseGuard.setEnabled(false);
3734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 Process.setArgV0("<pre-initialized>");
3736
3737 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003738 if (sMainThreadHandler == null) {
3739 sMainThreadHandler = new Handler();
3740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741
3742 ActivityThread thread = new ActivityThread();
3743 thread.attach(false);
3744
Dianne Hackborn287952c2010-09-22 22:34:31 -07003745 if (false) {
3746 Looper.myLooper().setMessageLogging(new
3747 LogPrinter(Log.DEBUG, "ActivityThread"));
3748 }
3749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 Looper.loop();
3751
3752 if (Process.supportsProcesses()) {
3753 throw new RuntimeException("Main thread loop unexpectedly exited");
3754 }
3755
3756 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003757 String name = (thread.mInitialApplication != null)
3758 ? thread.mInitialApplication.getPackageName()
3759 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003760 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 }
3762}