blob: 70e11dfdffd92c5b57b7093659aad08575d4ba75 [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
Bob Leee5408332009-09-04 18:31:17 -070098import dalvik.system.SamplingProfiler;
99
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100final class SuperNotCalledException extends AndroidRuntimeException {
101 public SuperNotCalledException(String msg) {
102 super(msg);
103 }
104}
105
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700106final class RemoteServiceException extends AndroidRuntimeException {
107 public RemoteServiceException(String msg) {
108 super(msg);
109 }
110}
111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112/**
113 * This manages the execution of the main thread in an
114 * application process, scheduling and executing activities,
115 * broadcasts, and other operations on it as the activity
116 * manager requests.
117 *
118 * {@hide}
119 */
120public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700121 /** @hide */
122 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700123 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700125 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700126 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700127 /** @hide */
128 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700129 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700130 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700131 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
133 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
134 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
135 private static final int LOG_ON_PAUSE_CALLED = 30021;
136 private static final int LOG_ON_RESUME_CALLED = 30022;
137
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700138 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700139
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700140 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700142 final ApplicationThread mAppThread = new ApplicationThread();
143 final Looper mLooper = Looper.myLooper();
144 final H mH = new H();
145 final HashMap<IBinder, ActivityClientRecord> mActivities
146 = new HashMap<IBinder, ActivityClientRecord>();
147 // List of new activities (via ActivityRecord.nextIdle) that should
148 // be reported when next we idle.
149 ActivityClientRecord mNewActivities = null;
150 // Number of activities that are currently visible on-screen.
151 int mNumVisibleActivities = 0;
152 final HashMap<IBinder, Service> mServices
153 = new HashMap<IBinder, Service>();
154 AppBindData mBoundApplication;
155 Configuration mConfiguration;
156 Configuration mResConfiguration;
157 Application mInitialApplication;
158 final ArrayList<Application> mAllApplications
159 = new ArrayList<Application>();
160 // set of instantiated backup agents, keyed by package name
161 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700162 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700163 Instrumentation mInstrumentation;
164 String mInstrumentationAppDir = null;
165 String mInstrumentationAppPackage = null;
166 String mInstrumentedAppDir = null;
167 boolean mSystemThread = false;
168 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700170 // These can be accessed by multiple threads; mPackages is the lock.
171 // XXX For now we keep around information about all packages we have
172 // seen, not removing entries from this map.
173 final HashMap<String, WeakReference<LoadedApk>> mPackages
174 = new HashMap<String, WeakReference<LoadedApk>>();
175 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
176 = new HashMap<String, WeakReference<LoadedApk>>();
177 Display mDisplay = null;
178 DisplayMetrics mDisplayMetrics = null;
179 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
180 = new HashMap<ResourcesKey, WeakReference<Resources> >();
181 final ArrayList<ActivityClientRecord> mRelaunchingActivities
182 = new ArrayList<ActivityClientRecord>();
183 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700185 // The lock of mProviderMap protects the following variables.
186 final HashMap<String, ProviderClientRecord> mProviderMap
187 = new HashMap<String, ProviderClientRecord>();
188 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
189 = new HashMap<IBinder, ProviderRefCount>();
190 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
191 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700193 final GcIdler mGcIdler = new GcIdler();
194 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700196 static Handler sMainThreadHandler; // set once in main()
197
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700198 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700200 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 Intent intent;
202 Bundle state;
203 Activity activity;
204 Window window;
205 Activity parent;
206 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700207 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 boolean paused;
209 boolean stopped;
210 boolean hideForNow;
211 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700212 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700213 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
215 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700216 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
218 List<ResultInfo> pendingResults;
219 List<Intent> pendingIntents;
220
221 boolean startsNotResumed;
222 boolean isForward;
223
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700224 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 parent = null;
226 embeddedID = null;
227 paused = false;
228 stopped = false;
229 hideForNow = false;
230 nextIdle = null;
231 }
232
233 public String toString() {
234 ComponentName componentName = intent.getComponent();
235 return "ActivityRecord{"
236 + Integer.toHexString(System.identityHashCode(this))
237 + " token=" + token + " " + (componentName == null
238 ? "no component name" : componentName.toShortString())
239 + "}";
240 }
241 }
242
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700243 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 final String mName;
245 final IContentProvider mProvider;
246 final ContentProvider mLocalProvider;
247
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700248 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 ContentProvider localProvider) {
250 mName = name;
251 mProvider = provider;
252 mLocalProvider = localProvider;
253 }
254
255 public void binderDied() {
256 removeDeadProvider(mName, mProvider);
257 }
258 }
259
260 private static final class NewIntentData {
261 List<Intent> intents;
262 IBinder token;
263 public String toString() {
264 return "NewIntentData{intents=" + intents + " token=" + token + "}";
265 }
266 }
267
Dianne Hackborne829fef2010-10-26 17:44:01 -0700268 private static final class ReceiverData extends BroadcastReceiver.PendingResult {
269 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
270 boolean ordered, boolean sticky, IBinder token) {
271 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
272 this.intent = intent;
273 }
274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 Intent intent;
276 ActivityInfo info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 public String toString() {
278 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700279 info.packageName + " resultCode=" + getResultCode()
280 + " resultData=" + getResultData() + " resultExtras="
281 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 }
283 }
284
Christopher Tate181fafa2009-05-14 11:12:14 -0700285 private static final class CreateBackupAgentData {
286 ApplicationInfo appInfo;
287 int backupMode;
288 public String toString() {
289 return "CreateBackupAgentData{appInfo=" + appInfo
290 + " backupAgent=" + appInfo.backupAgentName
291 + " mode=" + backupMode + "}";
292 }
293 }
Bob Leee5408332009-09-04 18:31:17 -0700294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 private static final class CreateServiceData {
296 IBinder token;
297 ServiceInfo info;
298 Intent intent;
299 public String toString() {
300 return "CreateServiceData{token=" + token + " className="
301 + info.name + " packageName=" + info.packageName
302 + " intent=" + intent + "}";
303 }
304 }
305
306 private static final class BindServiceData {
307 IBinder token;
308 Intent intent;
309 boolean rebind;
310 public String toString() {
311 return "BindServiceData{token=" + token + " intent=" + intent + "}";
312 }
313 }
314
315 private static final class ServiceArgsData {
316 IBinder token;
317 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700318 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 Intent args;
320 public String toString() {
321 return "ServiceArgsData{token=" + token + " startId=" + startId
322 + " args=" + args + "}";
323 }
324 }
325
326 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700327 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 String processName;
329 ApplicationInfo appInfo;
330 List<ProviderInfo> providers;
331 ComponentName instrumentationName;
332 String profileFile;
333 Bundle instrumentationArgs;
334 IInstrumentationWatcher instrumentationWatcher;
335 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700336 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 Configuration config;
338 boolean handlingProfiling;
339 public String toString() {
340 return "AppBindData{appInfo=" + appInfo + "}";
341 }
342 }
343
Dianne Hackborn625ac272010-09-17 18:29:22 -0700344 private static final class DumpComponentInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 FileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700346 IBinder token;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 String[] args;
348 boolean dumped;
349 }
350
351 private static final class ResultData {
352 IBinder token;
353 List<ResultInfo> results;
354 public String toString() {
355 return "ResultData{token=" + token + " results" + results + "}";
356 }
357 }
358
359 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800360 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 String what;
362 String who;
363 }
364
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700365 private static final class ProfilerControlData {
366 String path;
367 ParcelFileDescriptor fd;
368 }
369
Andy McFadden824c5102010-07-09 16:26:57 -0700370 private static final class DumpHeapData {
371 String path;
372 ParcelFileDescriptor fd;
373 }
374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 private final class ApplicationThread extends ApplicationThreadNative {
376 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
377 private static final String ONE_COUNT_COLUMN = "%17s %8d";
378 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700379 private static final String TWO_COUNT_COLUMNS_DB = "%20s %8d %20s %8d";
380 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 // Formatting for checkin service - update version if row format changes
383 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 public final void schedulePauseActivity(IBinder token, boolean finished,
386 boolean userLeaving, int configChanges) {
387 queueOrSendMessage(
388 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
389 token,
390 (userLeaving ? 1 : 0),
391 configChanges);
392 }
393
394 public final void scheduleStopActivity(IBinder token, boolean showWindow,
395 int configChanges) {
396 queueOrSendMessage(
397 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
398 token, 0, configChanges);
399 }
400
401 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
402 queueOrSendMessage(
403 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
404 token);
405 }
406
407 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
408 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
409 }
410
411 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
412 ResultData res = new ResultData();
413 res.token = token;
414 res.results = results;
415 queueOrSendMessage(H.SEND_RESULT, res);
416 }
417
418 // we use token to identify this activity without having to send the
419 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700420 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
422 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700423 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424
425 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700426 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 r.intent = intent;
428 r.activityInfo = info;
429 r.state = state;
430
431 r.pendingResults = pendingResults;
432 r.pendingIntents = pendingNewIntents;
433
434 r.startsNotResumed = notResumed;
435 r.isForward = isForward;
436
437 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
438 }
439
440 public final void scheduleRelaunchActivity(IBinder token,
441 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800442 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700443 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444
445 r.token = token;
446 r.pendingResults = pendingResults;
447 r.pendingIntents = pendingNewIntents;
448 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800449 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800451 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 mRelaunchingActivities.add(r);
453 }
Bob Leee5408332009-09-04 18:31:17 -0700454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
456 }
457
458 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
459 NewIntentData data = new NewIntentData();
460 data.intents = intents;
461 data.token = token;
462
463 queueOrSendMessage(H.NEW_INTENT, data);
464 }
465
466 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
467 int configChanges) {
468 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
469 configChanges);
470 }
471
472 public final void scheduleReceiver(Intent intent, ActivityInfo info,
473 int resultCode, String data, Bundle extras, boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700474 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
475 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 r.info = info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 queueOrSendMessage(H.RECEIVER, r);
478 }
479
Christopher Tate181fafa2009-05-14 11:12:14 -0700480 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
481 CreateBackupAgentData d = new CreateBackupAgentData();
482 d.appInfo = app;
483 d.backupMode = backupMode;
484
485 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
486 }
487
488 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
489 CreateBackupAgentData d = new CreateBackupAgentData();
490 d.appInfo = app;
491
492 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
493 }
494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 public final void scheduleCreateService(IBinder token,
496 ServiceInfo info) {
497 CreateServiceData s = new CreateServiceData();
498 s.token = token;
499 s.info = info;
500
501 queueOrSendMessage(H.CREATE_SERVICE, s);
502 }
503
504 public final void scheduleBindService(IBinder token, Intent intent,
505 boolean rebind) {
506 BindServiceData s = new BindServiceData();
507 s.token = token;
508 s.intent = intent;
509 s.rebind = rebind;
510
511 queueOrSendMessage(H.BIND_SERVICE, s);
512 }
513
514 public final void scheduleUnbindService(IBinder token, Intent intent) {
515 BindServiceData s = new BindServiceData();
516 s.token = token;
517 s.intent = intent;
518
519 queueOrSendMessage(H.UNBIND_SERVICE, s);
520 }
521
522 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700523 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 ServiceArgsData s = new ServiceArgsData();
525 s.token = token;
526 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700527 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 s.args = args;
529
530 queueOrSendMessage(H.SERVICE_ARGS, s);
531 }
532
533 public final void scheduleStopService(IBinder token) {
534 queueOrSendMessage(H.STOP_SERVICE, token);
535 }
536
537 public final void bindApplication(String processName,
538 ApplicationInfo appInfo, List<ProviderInfo> providers,
539 ComponentName instrumentationName, String profileFile,
540 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700541 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543
544 if (services != null) {
545 // Setup the service cache in the ServiceManager
546 ServiceManager.initServiceCache(services);
547 }
548
549 AppBindData data = new AppBindData();
550 data.processName = processName;
551 data.appInfo = appInfo;
552 data.providers = providers;
553 data.instrumentationName = instrumentationName;
554 data.profileFile = profileFile;
555 data.instrumentationArgs = instrumentationArgs;
556 data.instrumentationWatcher = instrumentationWatcher;
557 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700558 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 data.config = config;
560 queueOrSendMessage(H.BIND_APPLICATION, data);
561 }
562
563 public final void scheduleExit() {
564 queueOrSendMessage(H.EXIT_APPLICATION, null);
565 }
566
Christopher Tate5e1ab332009-09-01 20:32:49 -0700567 public final void scheduleSuicide() {
568 queueOrSendMessage(H.SUICIDE, null);
569 }
570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 public void requestThumbnail(IBinder token) {
572 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
573 }
574
575 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800576 synchronized (mPackages) {
577 if (mPendingConfiguration == null ||
578 mPendingConfiguration.isOtherSeqNewer(config)) {
579 mPendingConfiguration = config;
580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 }
582 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
583 }
584
585 public void updateTimeZone() {
586 TimeZone.setDefault(null);
587 }
588
Robert Greenwalt03595d02010-11-02 14:08:23 -0700589 public void clearDnsCache() {
590 // a non-standard API to get this to libcore
591 InetAddress.clearDnsCache();
592 }
593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 public void processInBackground() {
595 mH.removeMessages(H.GC_WHEN_IDLE);
596 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
597 }
598
599 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700600 DumpComponentInfo data = new DumpComponentInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 data.fd = fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700602 data.token = servicetoken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 data.args = args;
604 data.dumped = false;
605 queueOrSendMessage(H.DUMP_SERVICE, data);
606 synchronized (data) {
607 while (!data.dumped) {
608 try {
609 data.wait();
610 } catch (InterruptedException e) {
611 // no need to do anything here, we will keep waiting until
612 // dumped is set
613 }
614 }
615 }
616 }
617
618 // This function exists to make sure all receiver dispatching is
619 // correctly ordered, since these are one-way calls and the binder driver
620 // applies transaction ordering per object for such calls.
621 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700622 int resultCode, String dataStr, Bundle extras, boolean ordered,
623 boolean sticky) throws RemoteException {
624 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
Bob Leee5408332009-09-04 18:31:17 -0700626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 public void scheduleLowMemory() {
628 queueOrSendMessage(H.LOW_MEMORY, null);
629 }
630
631 public void scheduleActivityConfigurationChanged(IBinder token) {
632 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
633 }
634
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700635 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
636 ProfilerControlData pcd = new ProfilerControlData();
637 pcd.path = path;
638 pcd.fd = fd;
639 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800640 }
641
Andy McFadden824c5102010-07-09 16:26:57 -0700642 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
643 DumpHeapData dhd = new DumpHeapData();
644 dhd.path = path;
645 dhd.fd = fd;
646 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
647 }
648
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700649 public void setSchedulingGroup(int group) {
650 // Note: do this immediately, since going into the foreground
651 // should happen regardless of what pending work we have to do
652 // and the activity manager will wait for us to report back that
653 // we are done before sending us to the background.
654 try {
655 Process.setProcessGroup(Process.myPid(), group);
656 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800657 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700658 }
659 }
Bob Leee5408332009-09-04 18:31:17 -0700660
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700661 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
662 Debug.getMemoryInfo(outInfo);
663 }
Bob Leee5408332009-09-04 18:31:17 -0700664
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700665 public void dispatchPackageBroadcast(int cmd, String[] packages) {
666 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
667 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700668
669 public void scheduleCrash(String msg) {
670 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
671 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700672
673 public void dumpActivity(FileDescriptor fd, IBinder activitytoken, String[] args) {
674 DumpComponentInfo data = new DumpComponentInfo();
675 data.fd = fd;
676 data.token = activitytoken;
677 data.args = args;
678 data.dumped = false;
679 queueOrSendMessage(H.DUMP_ACTIVITY, data);
680 synchronized (data) {
681 while (!data.dumped) {
682 try {
683 data.wait();
684 } catch (InterruptedException e) {
685 // no need to do anything here, we will keep waiting until
686 // dumped is set
687 }
688 }
689 }
690 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 @Override
693 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
694 long nativeMax = Debug.getNativeHeapSize() / 1024;
695 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
696 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
697
698 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
699 Debug.getMemoryInfo(memInfo);
700
701 final int nativeShared = memInfo.nativeSharedDirty;
702 final int dalvikShared = memInfo.dalvikSharedDirty;
703 final int otherShared = memInfo.otherSharedDirty;
704
705 final int nativePrivate = memInfo.nativePrivateDirty;
706 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
707 final int otherPrivate = memInfo.otherPrivateDirty;
708
709 Runtime runtime = Runtime.getRuntime();
710
711 long dalvikMax = runtime.totalMemory() / 1024;
712 long dalvikFree = runtime.freeMemory() / 1024;
713 long dalvikAllocated = dalvikMax - dalvikFree;
714 long viewInstanceCount = ViewDebug.getViewInstanceCount();
715 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700716 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
717 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 int globalAssetCount = AssetManager.getGlobalAssetCount();
719 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
720 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
721 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
722 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700723 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800725 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 // Check to see if we were called by checkin server. If so, print terse format.
728 boolean doCheckinFormat = false;
729 if (args != null) {
730 for (String arg : args) {
731 if ("-c".equals(arg)) doCheckinFormat = true;
732 }
733 }
Bob Leee5408332009-09-04 18:31:17 -0700734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 // For checkin, we print one long comma-separated list of values
736 if (doCheckinFormat) {
737 // NOTE: if you change anything significant below, also consider changing
738 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700739 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 // Header
743 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
744 pw.print(Process.myPid()); pw.print(',');
745 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 // Heap info - max
748 pw.print(nativeMax); pw.print(',');
749 pw.print(dalvikMax); pw.print(',');
750 pw.print("N/A,");
751 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 // Heap info - allocated
754 pw.print(nativeAllocated); pw.print(',');
755 pw.print(dalvikAllocated); pw.print(',');
756 pw.print("N/A,");
757 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 // Heap info - free
760 pw.print(nativeFree); pw.print(',');
761 pw.print(dalvikFree); pw.print(',');
762 pw.print("N/A,");
763 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 // Heap info - proportional set size
766 pw.print(memInfo.nativePss); pw.print(',');
767 pw.print(memInfo.dalvikPss); pw.print(',');
768 pw.print(memInfo.otherPss); pw.print(',');
769 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700772 pw.print(nativeShared); pw.print(',');
773 pw.print(dalvikShared); pw.print(',');
774 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700778 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 pw.print(dalvikPrivate); pw.print(',');
780 pw.print(otherPrivate); pw.print(',');
781 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 // Object counts
784 pw.print(viewInstanceCount); pw.print(',');
785 pw.print(viewRootInstanceCount); pw.print(',');
786 pw.print(appContextInstanceCount); pw.print(',');
787 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 pw.print(globalAssetCount); pw.print(',');
790 pw.print(globalAssetManagerCount); pw.print(',');
791 pw.print(binderLocalObjectCount); pw.print(',');
792 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 pw.print(binderDeathObjectCount); pw.print(',');
795 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 // SQL
798 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800799 pw.print(stats.memoryUsed / 1024); pw.print(',');
800 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
801 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
802 for (int i = 0; i < stats.dbStats.size(); i++) {
803 DbStats dbStats = stats.dbStats.get(i);
804 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700805 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800806 pw.print(',');
807 }
Bob Leee5408332009-09-04 18:31:17 -0700808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 return;
810 }
Bob Leee5408332009-09-04 18:31:17 -0700811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 // otherwise, show human-readable format
813 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
814 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
815 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
816 nativeAllocated + dalvikAllocated);
817 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
818 nativeFree + dalvikFree);
819
820 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
821 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
822
823 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
824 nativeShared + dalvikShared + otherShared);
825 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
826 nativePrivate + dalvikPrivate + otherPrivate);
827
828 pw.println(" ");
829 pw.println(" Objects");
830 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
831 viewRootInstanceCount);
832
833 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
834 "Activities:", activityInstanceCount);
835
836 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
837 "AssetManagers:", globalAssetManagerCount);
838
839 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
840 "Proxy Binders:", binderProxyObjectCount);
841 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
842
843 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 // SQLite mem info
846 pw.println(" ");
847 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700848 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800849 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700850 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
851 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800852 pw.println(" ");
853 int N = stats.dbStats.size();
854 if (N > 0) {
855 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700856 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
857 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800858 for (int i = 0; i < N; i++) {
859 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700860 printRow(pw, DB_INFO_FORMAT,
861 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
862 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
863 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
864 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800865 }
866 }
Bob Leee5408332009-09-04 18:31:17 -0700867
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700868 // Asset details.
869 String assetAlloc = AssetManager.getAssetAllocations();
870 if (assetAlloc != null) {
871 pw.println(" ");
872 pw.println(" Asset Allocations");
873 pw.print(assetAlloc);
874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 }
876
877 private void printRow(PrintWriter pw, String format, Object...objs) {
878 pw.println(String.format(format, objs));
879 }
880 }
881
882 private final class H extends Handler {
883 public static final int LAUNCH_ACTIVITY = 100;
884 public static final int PAUSE_ACTIVITY = 101;
885 public static final int PAUSE_ACTIVITY_FINISHING= 102;
886 public static final int STOP_ACTIVITY_SHOW = 103;
887 public static final int STOP_ACTIVITY_HIDE = 104;
888 public static final int SHOW_WINDOW = 105;
889 public static final int HIDE_WINDOW = 106;
890 public static final int RESUME_ACTIVITY = 107;
891 public static final int SEND_RESULT = 108;
892 public static final int DESTROY_ACTIVITY = 109;
893 public static final int BIND_APPLICATION = 110;
894 public static final int EXIT_APPLICATION = 111;
895 public static final int NEW_INTENT = 112;
896 public static final int RECEIVER = 113;
897 public static final int CREATE_SERVICE = 114;
898 public static final int SERVICE_ARGS = 115;
899 public static final int STOP_SERVICE = 116;
900 public static final int REQUEST_THUMBNAIL = 117;
901 public static final int CONFIGURATION_CHANGED = 118;
902 public static final int CLEAN_UP_CONTEXT = 119;
903 public static final int GC_WHEN_IDLE = 120;
904 public static final int BIND_SERVICE = 121;
905 public static final int UNBIND_SERVICE = 122;
906 public static final int DUMP_SERVICE = 123;
907 public static final int LOW_MEMORY = 124;
908 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
909 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800910 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700911 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700912 public static final int DESTROY_BACKUP_AGENT = 129;
913 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700914 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800915 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700916 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700917 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700918 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700919 public static final int DUMP_ACTIVITY = 136;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700921 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 switch (code) {
923 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
924 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
925 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
926 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
927 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
928 case SHOW_WINDOW: return "SHOW_WINDOW";
929 case HIDE_WINDOW: return "HIDE_WINDOW";
930 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
931 case SEND_RESULT: return "SEND_RESULT";
932 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
933 case BIND_APPLICATION: return "BIND_APPLICATION";
934 case EXIT_APPLICATION: return "EXIT_APPLICATION";
935 case NEW_INTENT: return "NEW_INTENT";
936 case RECEIVER: return "RECEIVER";
937 case CREATE_SERVICE: return "CREATE_SERVICE";
938 case SERVICE_ARGS: return "SERVICE_ARGS";
939 case STOP_SERVICE: return "STOP_SERVICE";
940 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
941 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
942 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
943 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
944 case BIND_SERVICE: return "BIND_SERVICE";
945 case UNBIND_SERVICE: return "UNBIND_SERVICE";
946 case DUMP_SERVICE: return "DUMP_SERVICE";
947 case LOW_MEMORY: return "LOW_MEMORY";
948 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
949 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800950 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700951 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
952 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700953 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700954 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800955 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700956 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700957 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -0700958 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -0700959 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 }
961 }
962 return "(unknown)";
963 }
964 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700965 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 switch (msg.what) {
967 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700968 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969
970 r.packageInfo = getPackageInfoNoCheck(
971 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700972 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 } break;
974 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700975 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 handleRelaunchActivity(r, msg.arg1);
977 } break;
978 case PAUSE_ACTIVITY:
979 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700980 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 break;
982 case PAUSE_ACTIVITY_FINISHING:
983 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
984 break;
985 case STOP_ACTIVITY_SHOW:
986 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
987 break;
988 case STOP_ACTIVITY_HIDE:
989 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
990 break;
991 case SHOW_WINDOW:
992 handleWindowVisibility((IBinder)msg.obj, true);
993 break;
994 case HIDE_WINDOW:
995 handleWindowVisibility((IBinder)msg.obj, false);
996 break;
997 case RESUME_ACTIVITY:
998 handleResumeActivity((IBinder)msg.obj, true,
999 msg.arg1 != 0);
1000 break;
1001 case SEND_RESULT:
1002 handleSendResult((ResultData)msg.obj);
1003 break;
1004 case DESTROY_ACTIVITY:
1005 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1006 msg.arg2, false);
1007 break;
1008 case BIND_APPLICATION:
1009 AppBindData data = (AppBindData)msg.obj;
1010 handleBindApplication(data);
1011 break;
1012 case EXIT_APPLICATION:
1013 if (mInitialApplication != null) {
1014 mInitialApplication.onTerminate();
1015 }
1016 Looper.myLooper().quit();
1017 break;
1018 case NEW_INTENT:
1019 handleNewIntent((NewIntentData)msg.obj);
1020 break;
1021 case RECEIVER:
1022 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001023 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 break;
1025 case CREATE_SERVICE:
1026 handleCreateService((CreateServiceData)msg.obj);
1027 break;
1028 case BIND_SERVICE:
1029 handleBindService((BindServiceData)msg.obj);
1030 break;
1031 case UNBIND_SERVICE:
1032 handleUnbindService((BindServiceData)msg.obj);
1033 break;
1034 case SERVICE_ARGS:
1035 handleServiceArgs((ServiceArgsData)msg.obj);
1036 break;
1037 case STOP_SERVICE:
1038 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001039 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 break;
1041 case REQUEST_THUMBNAIL:
1042 handleRequestThumbnail((IBinder)msg.obj);
1043 break;
1044 case CONFIGURATION_CHANGED:
1045 handleConfigurationChanged((Configuration)msg.obj);
1046 break;
1047 case CLEAN_UP_CONTEXT:
1048 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1049 cci.context.performFinalCleanup(cci.who, cci.what);
1050 break;
1051 case GC_WHEN_IDLE:
1052 scheduleGcIdler();
1053 break;
1054 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001055 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 break;
1057 case LOW_MEMORY:
1058 handleLowMemory();
1059 break;
1060 case ACTIVITY_CONFIGURATION_CHANGED:
1061 handleActivityConfigurationChanged((IBinder)msg.obj);
1062 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001063 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001064 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001065 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001066 case CREATE_BACKUP_AGENT:
1067 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1068 break;
1069 case DESTROY_BACKUP_AGENT:
1070 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1071 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001072 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001073 Process.killProcess(Process.myPid());
1074 break;
1075 case REMOVE_PROVIDER:
1076 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001077 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001078 case ENABLE_JIT:
1079 ensureJitEnabled();
1080 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001081 case DISPATCH_PACKAGE_BROADCAST:
1082 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1083 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001084 case SCHEDULE_CRASH:
1085 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001086 case DUMP_HEAP:
1087 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1088 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001089 case DUMP_ACTIVITY:
1090 handleDumpActivity((DumpComponentInfo)msg.obj);
1091 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001093 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 }
Bob Leee5408332009-09-04 18:31:17 -07001095
1096 void maybeSnapshot() {
1097 if (mBoundApplication != null) {
Sen Hubde75702010-05-28 01:54:03 -07001098 // convert the *private* ActivityThread.PackageInfo to *public* known
1099 // android.content.pm.PackageInfo
1100 String packageName = mBoundApplication.info.mPackageName;
1101 android.content.pm.PackageInfo packageInfo = null;
1102 try {
1103 Context context = getSystemContext();
1104 if(context == null) {
1105 Log.e(TAG, "cannot get a valid context");
1106 return;
1107 }
1108 PackageManager pm = context.getPackageManager();
1109 if(pm == null) {
1110 Log.e(TAG, "cannot get a valid PackageManager");
1111 return;
1112 }
1113 packageInfo = pm.getPackageInfo(
1114 packageName, PackageManager.GET_ACTIVITIES);
1115 } catch (NameNotFoundException e) {
1116 Log.e(TAG, "cannot get package info for " + packageName, e);
1117 }
1118 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001119 }
1120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
1122
1123 private final class Idler implements MessageQueue.IdleHandler {
1124 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001125 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 if (a != null) {
1127 mNewActivities = null;
1128 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001129 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001131 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 TAG, "Reporting idle of " + a +
1133 " finished=" +
1134 (a.activity != null ? a.activity.mFinished : false));
1135 if (a.activity != null && !a.activity.mFinished) {
1136 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001137 am.activityIdle(a.token, a.createdConfig);
1138 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 } catch (RemoteException ex) {
1140 }
1141 }
1142 prev = a;
1143 a = a.nextIdle;
1144 prev.nextIdle = null;
1145 } while (a != null);
1146 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001147 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 return false;
1149 }
1150 }
1151
1152 final class GcIdler implements MessageQueue.IdleHandler {
1153 public final boolean queueIdle() {
1154 doGcIfNeeded();
1155 return false;
1156 }
1157 }
1158
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001159 private final static class ResourcesKey {
1160 final private String mResDir;
1161 final private float mScale;
1162 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001163
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001164 ResourcesKey(String resDir, float scale) {
1165 mResDir = resDir;
1166 mScale = scale;
1167 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1168 }
Bob Leee5408332009-09-04 18:31:17 -07001169
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001170 @Override
1171 public int hashCode() {
1172 return mHash;
1173 }
1174
1175 @Override
1176 public boolean equals(Object obj) {
1177 if (!(obj instanceof ResourcesKey)) {
1178 return false;
1179 }
1180 ResourcesKey peer = (ResourcesKey) obj;
1181 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1182 }
1183 }
1184
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001185 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001186 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001189 public static final String currentPackageName() {
1190 ActivityThread am = currentActivityThread();
1191 return (am != null && am.mBoundApplication != null)
1192 ? am.mBoundApplication.processName : null;
1193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001195 public static final Application currentApplication() {
1196 ActivityThread am = currentActivityThread();
1197 return am != null ? am.mInitialApplication : null;
1198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001200 public static IPackageManager getPackageManager() {
1201 if (sPackageManager != null) {
1202 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1203 return sPackageManager;
1204 }
1205 IBinder b = ServiceManager.getService("package");
1206 //Slog.v("PackageManager", "default service binder = " + b);
1207 sPackageManager = IPackageManager.Stub.asInterface(b);
1208 //Slog.v("PackageManager", "default service = " + sPackageManager);
1209 return sPackageManager;
1210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001212 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1213 if (mDisplayMetrics != null && !forceUpdate) {
1214 return mDisplayMetrics;
1215 }
1216 if (mDisplay == null) {
1217 WindowManager wm = WindowManagerImpl.getDefault();
1218 mDisplay = wm.getDefaultDisplay();
1219 }
1220 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1221 mDisplay.getMetrics(metrics);
1222 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1223 // + metrics.heightPixels + " den=" + metrics.density
1224 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1225 return metrics;
1226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001228 /**
1229 * Creates the top level Resources for applications with the given compatibility info.
1230 *
1231 * @param resDir the resource directory.
1232 * @param compInfo the compability info. It will use the default compatibility info when it's
1233 * null.
1234 */
1235 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1236 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1237 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001239 // Resources is app scale dependent.
1240 if (false) {
1241 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1242 + compInfo.applicationScale);
1243 }
1244 WeakReference<Resources> wr = mActiveResources.get(key);
1245 r = wr != null ? wr.get() : null;
1246 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1247 if (r != null && r.getAssets().isUpToDate()) {
1248 if (false) {
1249 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1250 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1251 }
1252 return r;
1253 }
1254 }
1255
1256 //if (r != null) {
1257 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1258 // + r + " " + resDir);
1259 //}
1260
1261 AssetManager assets = new AssetManager();
1262 if (assets.addAssetPath(resDir) == 0) {
1263 return null;
1264 }
1265
1266 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1267 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1268 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1269 if (false) {
1270 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1271 + r.getConfiguration() + " appScale="
1272 + r.getCompatibilityInfo().applicationScale);
1273 }
1274
1275 synchronized (mPackages) {
1276 WeakReference<Resources> wr = mActiveResources.get(key);
1277 Resources existing = wr != null ? wr.get() : null;
1278 if (existing != null && existing.getAssets().isUpToDate()) {
1279 // Someone else already created the resources while we were
1280 // unlocked; go ahead and use theirs.
1281 r.getAssets().close();
1282 return existing;
1283 }
1284
1285 // XXX need to remove entries when weak references go away
1286 mActiveResources.put(key, new WeakReference<Resources>(r));
1287 return r;
1288 }
1289 }
1290
1291 /**
1292 * Creates the top level resources for the given package.
1293 */
1294 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1295 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1296 }
1297
1298 final Handler getHandler() {
1299 return mH;
1300 }
1301
1302 public final LoadedApk getPackageInfo(String packageName, int flags) {
1303 synchronized (mPackages) {
1304 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1306 ref = mPackages.get(packageName);
1307 } else {
1308 ref = mResourcePackages.get(packageName);
1309 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001310 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001311 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001312 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1313 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 if (packageInfo != null && (packageInfo.mResources == null
1315 || packageInfo.mResources.getAssets().isUpToDate())) {
1316 if (packageInfo.isSecurityViolation()
1317 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1318 throw new SecurityException(
1319 "Requesting code from " + packageName
1320 + " to be run in process "
1321 + mBoundApplication.processName
1322 + "/" + mBoundApplication.appInfo.uid);
1323 }
1324 return packageInfo;
1325 }
1326 }
1327
1328 ApplicationInfo ai = null;
1329 try {
1330 ai = getPackageManager().getApplicationInfo(packageName,
1331 PackageManager.GET_SHARED_LIBRARY_FILES);
1332 } catch (RemoteException e) {
1333 }
1334
1335 if (ai != null) {
1336 return getPackageInfo(ai, flags);
1337 }
1338
1339 return null;
1340 }
1341
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001342 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1344 boolean securityViolation = includeCode && ai.uid != 0
1345 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1346 ? ai.uid != mBoundApplication.appInfo.uid : true);
1347 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1348 |Context.CONTEXT_IGNORE_SECURITY))
1349 == Context.CONTEXT_INCLUDE_CODE) {
1350 if (securityViolation) {
1351 String msg = "Requesting code from " + ai.packageName
1352 + " (with uid " + ai.uid + ")";
1353 if (mBoundApplication != null) {
1354 msg = msg + " to be run in process "
1355 + mBoundApplication.processName + " (with uid "
1356 + mBoundApplication.appInfo.uid + ")";
1357 }
1358 throw new SecurityException(msg);
1359 }
1360 }
1361 return getPackageInfo(ai, null, securityViolation, includeCode);
1362 }
1363
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001364 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 return getPackageInfo(ai, null, false, true);
1366 }
1367
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001368 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1370 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001371 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 if (includeCode) {
1373 ref = mPackages.get(aInfo.packageName);
1374 } else {
1375 ref = mResourcePackages.get(aInfo.packageName);
1376 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001377 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 if (packageInfo == null || (packageInfo.mResources != null
1379 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001380 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 : "Loading resource-only package ") + aInfo.packageName
1382 + " (in " + (mBoundApplication != null
1383 ? mBoundApplication.processName : null)
1384 + ")");
1385 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001386 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 securityViolation, includeCode &&
1388 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1389 if (includeCode) {
1390 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001391 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 } else {
1393 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001394 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396 }
1397 return packageInfo;
1398 }
1399 }
1400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 ActivityThread() {
1402 }
1403
1404 public ApplicationThread getApplicationThread()
1405 {
1406 return mAppThread;
1407 }
1408
1409 public Instrumentation getInstrumentation()
1410 {
1411 return mInstrumentation;
1412 }
1413
1414 public Configuration getConfiguration() {
1415 return mConfiguration;
1416 }
1417
1418 public boolean isProfiling() {
1419 return mBoundApplication != null && mBoundApplication.profileFile != null;
1420 }
1421
1422 public String getProfileFilePath() {
1423 return mBoundApplication.profileFile;
1424 }
1425
1426 public Looper getLooper() {
1427 return mLooper;
1428 }
1429
1430 public Application getApplication() {
1431 return mInitialApplication;
1432 }
Bob Leee5408332009-09-04 18:31:17 -07001433
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001434 public String getProcessName() {
1435 return mBoundApplication.processName;
1436 }
Bob Leee5408332009-09-04 18:31:17 -07001437
Dianne Hackborn21556372010-02-04 16:34:40 -08001438 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 synchronized (this) {
1440 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001441 ContextImpl context =
1442 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001443 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 context.init(info, null, this);
1445 context.getResources().updateConfiguration(
1446 getConfiguration(), getDisplayMetricsLocked(false));
1447 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001448 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 // + ": " + context.getResources().getConfiguration());
1450 }
1451 }
1452 return mSystemContext;
1453 }
1454
Mike Cleron432b7132009-09-24 15:28:29 -07001455 public void installSystemApplicationInfo(ApplicationInfo info) {
1456 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001457 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001458 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001459 }
1460 }
1461
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001462 void ensureJitEnabled() {
1463 if (!mJitEnabled) {
1464 mJitEnabled = true;
1465 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1466 }
1467 }
1468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 void scheduleGcIdler() {
1470 if (!mGcIdlerScheduled) {
1471 mGcIdlerScheduled = true;
1472 Looper.myQueue().addIdleHandler(mGcIdler);
1473 }
1474 mH.removeMessages(H.GC_WHEN_IDLE);
1475 }
1476
1477 void unscheduleGcIdler() {
1478 if (mGcIdlerScheduled) {
1479 mGcIdlerScheduled = false;
1480 Looper.myQueue().removeIdleHandler(mGcIdler);
1481 }
1482 mH.removeMessages(H.GC_WHEN_IDLE);
1483 }
1484
1485 void doGcIfNeeded() {
1486 mGcIdlerScheduled = false;
1487 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001488 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 // + "m now=" + now);
1490 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001491 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 BinderInternal.forceGc("bg");
1493 }
1494 }
1495
1496 public final ActivityInfo resolveActivityInfo(Intent intent) {
1497 ActivityInfo aInfo = intent.resolveActivityInfo(
1498 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1499 if (aInfo == null) {
1500 // Throw an exception.
1501 Instrumentation.checkStartActivityResult(
1502 IActivityManager.START_CLASS_NOT_FOUND, intent);
1503 }
1504 return aInfo;
1505 }
Bob Leee5408332009-09-04 18:31:17 -07001506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001509 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001510 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001512 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 r.intent = intent;
1514 r.state = state;
1515 r.parent = parent;
1516 r.embeddedID = id;
1517 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001518 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 if (localLOGV) {
1520 ComponentName compname = intent.getComponent();
1521 String name;
1522 if (compname != null) {
1523 name = compname.toShortString();
1524 } else {
1525 name = "(Intent " + intent + ").getComponent() returned null";
1526 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001527 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 + ", comp=" + name
1529 + ", token=" + token);
1530 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001531 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 }
1533
1534 public final Activity getActivity(IBinder token) {
1535 return mActivities.get(token).activity;
1536 }
1537
1538 public final void sendActivityResult(
1539 IBinder token, String id, int requestCode,
1540 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001541 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001542 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1544 list.add(new ResultInfo(id, requestCode, resultCode, data));
1545 mAppThread.scheduleSendResult(token, list);
1546 }
1547
1548 // if the thread hasn't started yet, we don't have the handler, so just
1549 // save the messages until we're ready.
1550 private final void queueOrSendMessage(int what, Object obj) {
1551 queueOrSendMessage(what, obj, 0, 0);
1552 }
1553
1554 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1555 queueOrSendMessage(what, obj, arg1, 0);
1556 }
1557
1558 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1559 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001560 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1562 + ": " + arg1 + " / " + obj);
1563 Message msg = Message.obtain();
1564 msg.what = what;
1565 msg.obj = obj;
1566 msg.arg1 = arg1;
1567 msg.arg2 = arg2;
1568 mH.sendMessage(msg);
1569 }
1570 }
1571
Dianne Hackborn21556372010-02-04 16:34:40 -08001572 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 String what) {
1574 ContextCleanupInfo cci = new ContextCleanupInfo();
1575 cci.context = context;
1576 cci.who = who;
1577 cci.what = what;
1578 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1579 }
1580
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001581 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1583
1584 ActivityInfo aInfo = r.activityInfo;
1585 if (r.packageInfo == null) {
1586 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1587 Context.CONTEXT_INCLUDE_CODE);
1588 }
Bob Leee5408332009-09-04 18:31:17 -07001589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 ComponentName component = r.intent.getComponent();
1591 if (component == null) {
1592 component = r.intent.resolveActivity(
1593 mInitialApplication.getPackageManager());
1594 r.intent.setComponent(component);
1595 }
1596
1597 if (r.activityInfo.targetActivity != null) {
1598 component = new ComponentName(r.activityInfo.packageName,
1599 r.activityInfo.targetActivity);
1600 }
1601
1602 Activity activity = null;
1603 try {
1604 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1605 activity = mInstrumentation.newActivity(
1606 cl, component.getClassName(), r.intent);
1607 r.intent.setExtrasClassLoader(cl);
1608 if (r.state != null) {
1609 r.state.setClassLoader(cl);
1610 }
1611 } catch (Exception e) {
1612 if (!mInstrumentation.onException(activity, e)) {
1613 throw new RuntimeException(
1614 "Unable to instantiate activity " + component
1615 + ": " + e.toString(), e);
1616 }
1617 }
1618
1619 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001620 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001621
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001622 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1623 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 TAG, r + ": app=" + app
1625 + ", appName=" + app.getPackageName()
1626 + ", pkg=" + r.packageInfo.getPackageName()
1627 + ", comp=" + r.intent.getComponent().toShortString()
1628 + ", dir=" + r.packageInfo.getAppDir());
1629
1630 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001631 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 appContext.init(r.packageInfo, r.token, this);
1633 appContext.setOuterContext(activity);
1634 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1635 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001636 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001637 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001638 activity.attach(appContext, this, getInstrumentation(), r.token,
1639 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001640 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001641
Christopher Tateb70f3df2009-04-07 16:07:59 -07001642 if (customIntent != null) {
1643 activity.mIntent = customIntent;
1644 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001645 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 activity.mStartedActivity = false;
1647 int theme = r.activityInfo.getThemeResource();
1648 if (theme != 0) {
1649 activity.setTheme(theme);
1650 }
1651
1652 activity.mCalled = false;
1653 mInstrumentation.callActivityOnCreate(activity, r.state);
1654 if (!activity.mCalled) {
1655 throw new SuperNotCalledException(
1656 "Activity " + r.intent.getComponent().toShortString() +
1657 " did not call through to super.onCreate()");
1658 }
1659 r.activity = activity;
1660 r.stopped = true;
1661 if (!r.activity.mFinished) {
1662 activity.performStart();
1663 r.stopped = false;
1664 }
1665 if (!r.activity.mFinished) {
1666 if (r.state != null) {
1667 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1668 }
1669 }
1670 if (!r.activity.mFinished) {
1671 activity.mCalled = false;
1672 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1673 if (!activity.mCalled) {
1674 throw new SuperNotCalledException(
1675 "Activity " + r.intent.getComponent().toShortString() +
1676 " did not call through to super.onPostCreate()");
1677 }
1678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680 r.paused = true;
1681
1682 mActivities.put(r.token, r);
1683
1684 } catch (SuperNotCalledException e) {
1685 throw e;
1686
1687 } catch (Exception e) {
1688 if (!mInstrumentation.onException(activity, e)) {
1689 throw new RuntimeException(
1690 "Unable to start activity " + component
1691 + ": " + e.toString(), e);
1692 }
1693 }
1694
1695 return activity;
1696 }
1697
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001698 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 // If we are getting ready to gc after going to the background, well
1700 // we are back active so skip it.
1701 unscheduleGcIdler();
1702
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001703 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001705 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706
1707 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001708 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001709 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 handleResumeActivity(r.token, false, r.isForward);
1711
1712 if (!r.activity.mFinished && r.startsNotResumed) {
1713 // The activity manager actually wants this one to start out
1714 // paused, because it needs to be visible but isn't in the
1715 // foreground. We accomplish this by going through the
1716 // normal startup (because activities expect to go through
1717 // onResume() the first time they run, before their window
1718 // is displayed), and then pausing it. However, in this case
1719 // we do -not- need to do the full pause cycle (of freezing
1720 // and such) because the activity manager assumes it can just
1721 // retain the current state it has.
1722 try {
1723 r.activity.mCalled = false;
1724 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001725 // We need to keep around the original state, in case
1726 // we need to be created again.
1727 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 if (!r.activity.mCalled) {
1729 throw new SuperNotCalledException(
1730 "Activity " + r.intent.getComponent().toShortString() +
1731 " did not call through to super.onPause()");
1732 }
1733
1734 } catch (SuperNotCalledException e) {
1735 throw e;
1736
1737 } catch (Exception e) {
1738 if (!mInstrumentation.onException(r.activity, e)) {
1739 throw new RuntimeException(
1740 "Unable to pause activity "
1741 + r.intent.getComponent().toShortString()
1742 + ": " + e.toString(), e);
1743 }
1744 }
1745 r.paused = true;
1746 }
1747 } else {
1748 // If there was an error, for any reason, tell the activity
1749 // manager to stop us.
1750 try {
1751 ActivityManagerNative.getDefault()
1752 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1753 } catch (RemoteException ex) {
1754 }
1755 }
1756 }
1757
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001758 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 List<Intent> intents) {
1760 final int N = intents.size();
1761 for (int i=0; i<N; i++) {
1762 Intent intent = intents.get(i);
1763 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001764 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1766 }
1767 }
1768
1769 public final void performNewIntents(IBinder token,
1770 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001771 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 if (r != null) {
1773 final boolean resumed = !r.paused;
1774 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001775 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 mInstrumentation.callActivityOnPause(r.activity);
1777 }
1778 deliverNewIntents(r, intents);
1779 if (resumed) {
1780 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001781 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 }
1783 }
1784 }
Bob Leee5408332009-09-04 18:31:17 -07001785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 private final void handleNewIntent(NewIntentData data) {
1787 performNewIntents(data.token, data.intents);
1788 }
1789
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001790 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
1791
1792 /**
1793 * Return the Intent that's currently being handled by a
1794 * BroadcastReceiver on this thread, or null if none.
1795 * @hide
1796 */
1797 public static Intent getIntentBeingBroadcast() {
1798 return sCurrentBroadcastIntent.get();
1799 }
1800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 private final void handleReceiver(ReceiverData data) {
1802 // If we are getting ready to gc after going to the background, well
1803 // we are back active so skip it.
1804 unscheduleGcIdler();
1805
1806 String component = data.intent.getComponent().getClassName();
1807
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001808 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 data.info.applicationInfo);
1810
1811 IActivityManager mgr = ActivityManagerNative.getDefault();
1812
1813 BroadcastReceiver receiver = null;
1814 try {
1815 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1816 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001817 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1819 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001820 if (DEBUG_BROADCAST) Slog.i(TAG,
1821 "Finishing failed broadcast to " + data.intent.getComponent());
1822 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 throw new RuntimeException(
1824 "Unable to instantiate receiver " + component
1825 + ": " + e.toString(), e);
1826 }
1827
1828 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001829 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001830
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001831 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 TAG, "Performing receive of " + data.intent
1833 + ": app=" + app
1834 + ", appName=" + app.getPackageName()
1835 + ", pkg=" + packageInfo.getPackageName()
1836 + ", comp=" + data.intent.getComponent().toShortString()
1837 + ", dir=" + packageInfo.getAppDir());
1838
Dianne Hackborn21556372010-02-04 16:34:40 -08001839 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001840 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001841 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 receiver.onReceive(context.getReceiverRestrictedContext(),
1843 data.intent);
1844 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001845 if (DEBUG_BROADCAST) Slog.i(TAG,
1846 "Finishing failed broadcast to " + data.intent.getComponent());
1847 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 if (!mInstrumentation.onException(receiver, e)) {
1849 throw new RuntimeException(
1850 "Unable to start receiver " + component
1851 + ": " + e.toString(), e);
1852 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001853 } finally {
1854 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856
Dianne Hackborne829fef2010-10-26 17:44:01 -07001857 if (receiver.getPendingResult() != null) {
1858 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 }
1860 }
1861
Christopher Tate181fafa2009-05-14 11:12:14 -07001862 // Instantiate a BackupAgent and tell it that it's alive
1863 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001864 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001865
1866 // no longer idle; we have backup work to do
1867 unscheduleGcIdler();
1868
1869 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001870 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001871 String packageName = packageInfo.mPackageName;
1872 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001873 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001874 + " already exists");
1875 return;
1876 }
Bob Leee5408332009-09-04 18:31:17 -07001877
Christopher Tate181fafa2009-05-14 11:12:14 -07001878 BackupAgent agent = null;
1879 String classname = data.appInfo.backupAgentName;
1880 if (classname == null) {
1881 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001882 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001883 + packageName);
1884 return;
1885 }
1886 classname = "android.app.FullBackupAgent";
1887 }
1888 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001889 IBinder binder = null;
1890 try {
1891 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1892 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1893
1894 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001895 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001896 + data.appInfo.backupAgentName);
1897
Dianne Hackborn21556372010-02-04 16:34:40 -08001898 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001899 context.init(packageInfo, null, this);
1900 context.setOuterContext(agent);
1901 agent.attach(context);
1902
1903 agent.onCreate();
1904 binder = agent.onBind();
1905 mBackupAgents.put(packageName, agent);
1906 } catch (Exception e) {
1907 // If this is during restore, fail silently; otherwise go
1908 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001909 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001910 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1911 throw e;
1912 }
1913 // falling through with 'binder' still null
1914 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001915
1916 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001917 try {
1918 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1919 } catch (RemoteException e) {
1920 // nothing to do.
1921 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001922 } catch (Exception e) {
1923 throw new RuntimeException("Unable to create BackupAgent "
1924 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1925 }
1926 }
1927
1928 // Tear down a BackupAgent
1929 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001930 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001931
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001932 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001933 String packageName = packageInfo.mPackageName;
1934 BackupAgent agent = mBackupAgents.get(packageName);
1935 if (agent != null) {
1936 try {
1937 agent.onDestroy();
1938 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001939 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001940 e.printStackTrace();
1941 }
1942 mBackupAgents.remove(packageName);
1943 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001944 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001945 }
1946 }
1947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 private final void handleCreateService(CreateServiceData data) {
1949 // If we are getting ready to gc after going to the background, well
1950 // we are back active so skip it.
1951 unscheduleGcIdler();
1952
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001953 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 data.info.applicationInfo);
1955 Service service = null;
1956 try {
1957 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1958 service = (Service) cl.loadClass(data.info.name).newInstance();
1959 } catch (Exception e) {
1960 if (!mInstrumentation.onException(service, e)) {
1961 throw new RuntimeException(
1962 "Unable to instantiate service " + data.info.name
1963 + ": " + e.toString(), e);
1964 }
1965 }
1966
1967 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001968 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969
Dianne Hackborn21556372010-02-04 16:34:40 -08001970 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 context.init(packageInfo, null, this);
1972
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001973 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 context.setOuterContext(service);
1975 service.attach(context, this, data.info.name, data.token, app,
1976 ActivityManagerNative.getDefault());
1977 service.onCreate();
1978 mServices.put(data.token, service);
1979 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001980 ActivityManagerNative.getDefault().serviceDoneExecuting(
1981 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 } catch (RemoteException e) {
1983 // nothing to do.
1984 }
1985 } catch (Exception e) {
1986 if (!mInstrumentation.onException(service, e)) {
1987 throw new RuntimeException(
1988 "Unable to create service " + data.info.name
1989 + ": " + e.toString(), e);
1990 }
1991 }
1992 }
1993
1994 private final void handleBindService(BindServiceData data) {
1995 Service s = mServices.get(data.token);
1996 if (s != null) {
1997 try {
1998 data.intent.setExtrasClassLoader(s.getClassLoader());
1999 try {
2000 if (!data.rebind) {
2001 IBinder binder = s.onBind(data.intent);
2002 ActivityManagerNative.getDefault().publishService(
2003 data.token, data.intent, binder);
2004 } else {
2005 s.onRebind(data.intent);
2006 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002007 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002009 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 } catch (RemoteException ex) {
2011 }
2012 } catch (Exception e) {
2013 if (!mInstrumentation.onException(s, e)) {
2014 throw new RuntimeException(
2015 "Unable to bind to service " + s
2016 + " with " + data.intent + ": " + e.toString(), e);
2017 }
2018 }
2019 }
2020 }
2021
2022 private final void handleUnbindService(BindServiceData data) {
2023 Service s = mServices.get(data.token);
2024 if (s != null) {
2025 try {
2026 data.intent.setExtrasClassLoader(s.getClassLoader());
2027 boolean doRebind = s.onUnbind(data.intent);
2028 try {
2029 if (doRebind) {
2030 ActivityManagerNative.getDefault().unbindFinished(
2031 data.token, data.intent, doRebind);
2032 } else {
2033 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002034 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
2036 } catch (RemoteException ex) {
2037 }
2038 } catch (Exception e) {
2039 if (!mInstrumentation.onException(s, e)) {
2040 throw new RuntimeException(
2041 "Unable to unbind to service " + s
2042 + " with " + data.intent + ": " + e.toString(), e);
2043 }
2044 }
2045 }
2046 }
2047
Dianne Hackborn625ac272010-09-17 18:29:22 -07002048 private void handleDumpService(DumpComponentInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002050 Service s = mServices.get(info.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 if (s != null) {
2052 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2053 s.dump(info.fd, pw, info.args);
2054 pw.close();
2055 }
2056 } finally {
2057 synchronized (info) {
2058 info.dumped = true;
2059 info.notifyAll();
2060 }
2061 }
2062 }
2063
Dianne Hackborn625ac272010-09-17 18:29:22 -07002064 private void handleDumpActivity(DumpComponentInfo info) {
2065 try {
2066 ActivityClientRecord r = mActivities.get(info.token);
2067 if (r != null && r.activity != null) {
2068 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2069 r.activity.dump(info.fd, pw, info.args);
2070 pw.close();
2071 }
2072 } finally {
2073 synchronized (info) {
2074 info.dumped = true;
2075 info.notifyAll();
2076 }
2077 }
2078 }
2079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 private final void handleServiceArgs(ServiceArgsData data) {
2081 Service s = mServices.get(data.token);
2082 if (s != null) {
2083 try {
2084 if (data.args != null) {
2085 data.args.setExtrasClassLoader(s.getClassLoader());
2086 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002087 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002088
2089 QueuedWork.waitToFinish();
2090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002092 ActivityManagerNative.getDefault().serviceDoneExecuting(
2093 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 } catch (RemoteException e) {
2095 // nothing to do.
2096 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002097 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 } catch (Exception e) {
2099 if (!mInstrumentation.onException(s, e)) {
2100 throw new RuntimeException(
2101 "Unable to start service " + s
2102 + " with " + data.args + ": " + e.toString(), e);
2103 }
2104 }
2105 }
2106 }
2107
2108 private final void handleStopService(IBinder token) {
2109 Service s = mServices.remove(token);
2110 if (s != null) {
2111 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002112 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 s.onDestroy();
2114 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002115 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002117 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002119
2120 QueuedWork.waitToFinish();
2121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002123 ActivityManagerNative.getDefault().serviceDoneExecuting(
2124 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 } catch (RemoteException e) {
2126 // nothing to do.
2127 }
2128 } catch (Exception e) {
2129 if (!mInstrumentation.onException(s, e)) {
2130 throw new RuntimeException(
2131 "Unable to stop service " + s
2132 + ": " + e.toString(), e);
2133 }
2134 }
2135 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002136 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 }
2138
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002139 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002141 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002142 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 + " finished=" + r.activity.mFinished);
2144 if (r != null && !r.activity.mFinished) {
2145 if (clearHide) {
2146 r.hideForNow = false;
2147 r.activity.mStartedActivity = false;
2148 }
2149 try {
2150 if (r.pendingIntents != null) {
2151 deliverNewIntents(r, r.pendingIntents);
2152 r.pendingIntents = null;
2153 }
2154 if (r.pendingResults != null) {
2155 deliverResults(r, r.pendingResults);
2156 r.pendingResults = null;
2157 }
2158 r.activity.performResume();
2159
Bob Leee5408332009-09-04 18:31:17 -07002160 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 r.paused = false;
2164 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 r.state = null;
2166 } catch (Exception e) {
2167 if (!mInstrumentation.onException(r.activity, e)) {
2168 throw new RuntimeException(
2169 "Unable to resume activity "
2170 + r.intent.getComponent().toShortString()
2171 + ": " + e.toString(), e);
2172 }
2173 }
2174 }
2175 return r;
2176 }
2177
2178 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2179 // If we are getting ready to gc after going to the background, well
2180 // we are back active so skip it.
2181 unscheduleGcIdler();
2182
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002183 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184
2185 if (r != null) {
2186 final Activity a = r.activity;
2187
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002188 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 TAG, "Resume " + r + " started activity: " +
2190 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2191 + ", finished: " + a.mFinished);
2192
2193 final int forwardBit = isForward ?
2194 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 // If the window hasn't yet been added to the window manager,
2197 // and this guy didn't finish itself or start another activity,
2198 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002199 boolean willBeVisible = !a.mStartedActivity;
2200 if (!willBeVisible) {
2201 try {
2202 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2203 a.getActivityToken());
2204 } catch (RemoteException e) {
2205 }
2206 }
2207 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 r.window = r.activity.getWindow();
2209 View decor = r.window.getDecorView();
2210 decor.setVisibility(View.INVISIBLE);
2211 ViewManager wm = a.getWindowManager();
2212 WindowManager.LayoutParams l = r.window.getAttributes();
2213 a.mDecor = decor;
2214 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2215 l.softInputMode |= forwardBit;
2216 if (a.mVisibleFromClient) {
2217 a.mWindowAdded = true;
2218 wm.addView(decor, l);
2219 }
2220
2221 // If the window has already been added, but during resume
2222 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002223 // window visible.
2224 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002225 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 TAG, "Launch " + r + " mStartedActivity set");
2227 r.hideForNow = true;
2228 }
2229
2230 // The window is now visible if it has been added, we are not
2231 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002232 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002233 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002235 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002236 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 performConfigurationChanged(r.activity, r.newConfig);
2238 r.newConfig = null;
2239 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002240 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 + isForward);
2242 WindowManager.LayoutParams l = r.window.getAttributes();
2243 if ((l.softInputMode
2244 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2245 != forwardBit) {
2246 l.softInputMode = (l.softInputMode
2247 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2248 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002249 if (r.activity.mVisibleFromClient) {
2250 ViewManager wm = a.getWindowManager();
2251 View decor = r.window.getDecorView();
2252 wm.updateViewLayout(decor, l);
2253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 }
2255 r.activity.mVisibleFromServer = true;
2256 mNumVisibleActivities++;
2257 if (r.activity.mVisibleFromClient) {
2258 r.activity.makeVisible();
2259 }
2260 }
2261
2262 r.nextIdle = mNewActivities;
2263 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002264 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 TAG, "Scheduling idle handler for " + r);
2266 Looper.myQueue().addIdleHandler(new Idler());
2267
2268 } else {
2269 // If an exception was thrown when trying to resume, then
2270 // just end this activity.
2271 try {
2272 ActivityManagerNative.getDefault()
2273 .finishActivity(token, Activity.RESULT_CANCELED, null);
2274 } catch (RemoteException ex) {
2275 }
2276 }
2277 }
2278
2279 private int mThumbnailWidth = -1;
2280 private int mThumbnailHeight = -1;
2281
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002282 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 Bitmap thumbnail = null;
2284 try {
2285 int w = mThumbnailWidth;
2286 int h;
2287 if (w < 0) {
2288 Resources res = r.activity.getResources();
2289 mThumbnailHeight = h =
2290 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2291
2292 mThumbnailWidth = w =
2293 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2294 } else {
2295 h = mThumbnailHeight;
2296 }
2297
Jim Miller0b2a6d02010-07-13 18:01:29 -07002298 // On platforms where we don't want thumbnails, set dims to (0,0)
2299 if ((w > 0) && (h > 0)) {
2300 View topView = r.activity.getWindow().getDecorView();
2301
2302 // Maximize bitmap by capturing in native aspect.
2303 if (topView.getWidth() >= topView.getHeight()) {
2304 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2305 } else {
2306 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2307 }
2308
2309 thumbnail.eraseColor(0);
2310 Canvas cv = new Canvas(thumbnail);
2311 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2312 thumbnail = null;
2313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 } catch (Exception e) {
2317 if (!mInstrumentation.onException(r.activity, e)) {
2318 throw new RuntimeException(
2319 "Unable to create thumbnail of "
2320 + r.intent.getComponent().toShortString()
2321 + ": " + e.toString(), e);
2322 }
2323 thumbnail = null;
2324 }
2325
2326 return thumbnail;
2327 }
2328
2329 private final void handlePauseActivity(IBinder token, boolean finished,
2330 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002331 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002333 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 if (userLeaving) {
2335 performUserLeavingActivity(r);
2336 }
Bob Leee5408332009-09-04 18:31:17 -07002337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 r.activity.mConfigChangeFlags |= configChanges;
2339 Bundle state = performPauseActivity(token, finished, true);
2340
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002341 // Make sure any pending writes are now committed.
2342 QueuedWork.waitToFinish();
2343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 // Tell the activity manager we have paused.
2345 try {
2346 ActivityManagerNative.getDefault().activityPaused(token, state);
2347 } catch (RemoteException ex) {
2348 }
2349 }
2350 }
2351
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002352 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 mInstrumentation.callActivityOnUserLeaving(r.activity);
2354 }
2355
2356 final Bundle performPauseActivity(IBinder token, boolean finished,
2357 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002358 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 return r != null ? performPauseActivity(r, finished, saveState) : null;
2360 }
2361
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002362 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 boolean saveState) {
2364 if (r.paused) {
2365 if (r.activity.mFinished) {
2366 // If we are finishing, we won't call onResume() in certain cases.
2367 // So here we likewise don't want to call onPause() if the activity
2368 // isn't resumed.
2369 return null;
2370 }
2371 RuntimeException e = new RuntimeException(
2372 "Performing pause of activity that is not resumed: "
2373 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002374 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 }
2376 Bundle state = null;
2377 if (finished) {
2378 r.activity.mFinished = true;
2379 }
2380 try {
2381 // Next have the activity save its current state and managed dialogs...
2382 if (!r.activity.mFinished && saveState) {
2383 state = new Bundle();
2384 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2385 r.state = state;
2386 }
2387 // Now we are idle.
2388 r.activity.mCalled = false;
2389 mInstrumentation.callActivityOnPause(r.activity);
2390 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2391 if (!r.activity.mCalled) {
2392 throw new SuperNotCalledException(
2393 "Activity " + r.intent.getComponent().toShortString() +
2394 " did not call through to super.onPause()");
2395 }
2396
2397 } catch (SuperNotCalledException e) {
2398 throw e;
2399
2400 } catch (Exception e) {
2401 if (!mInstrumentation.onException(r.activity, e)) {
2402 throw new RuntimeException(
2403 "Unable to pause activity "
2404 + r.intent.getComponent().toShortString()
2405 + ": " + e.toString(), e);
2406 }
2407 }
2408 r.paused = true;
2409 return state;
2410 }
2411
2412 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002413 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 performStopActivityInner(r, null, false);
2415 }
2416
2417 private static class StopInfo {
2418 Bitmap thumbnail;
2419 CharSequence description;
2420 }
2421
2422 private final class ProviderRefCount {
2423 public int count;
2424 ProviderRefCount(int pCount) {
2425 count = pCount;
2426 }
2427 }
2428
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002429 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002431 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 if (r != null) {
2433 if (!keepShown && r.stopped) {
2434 if (r.activity.mFinished) {
2435 // If we are finishing, we won't call onResume() in certain
2436 // cases. So here we likewise don't want to call onStop()
2437 // if the activity isn't resumed.
2438 return;
2439 }
2440 RuntimeException e = new RuntimeException(
2441 "Performing stop of activity that is not resumed: "
2442 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002443 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 }
2445
2446 if (info != null) {
2447 try {
2448 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002449 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 info.description = r.activity.onCreateDescription();
2451 } catch (Exception e) {
2452 if (!mInstrumentation.onException(r.activity, e)) {
2453 throw new RuntimeException(
2454 "Unable to save state of activity "
2455 + r.intent.getComponent().toShortString()
2456 + ": " + e.toString(), e);
2457 }
2458 }
2459 }
2460
2461 if (!keepShown) {
2462 try {
2463 // Now we are idle.
2464 r.activity.performStop();
2465 } catch (Exception e) {
2466 if (!mInstrumentation.onException(r.activity, e)) {
2467 throw new RuntimeException(
2468 "Unable to stop activity "
2469 + r.intent.getComponent().toShortString()
2470 + ": " + e.toString(), e);
2471 }
2472 }
2473 r.stopped = true;
2474 }
2475
2476 r.paused = true;
2477 }
2478 }
2479
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002480 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 View v = r.activity.mDecor;
2482 if (v != null) {
2483 if (show) {
2484 if (!r.activity.mVisibleFromServer) {
2485 r.activity.mVisibleFromServer = true;
2486 mNumVisibleActivities++;
2487 if (r.activity.mVisibleFromClient) {
2488 r.activity.makeVisible();
2489 }
2490 }
2491 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002492 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002493 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 performConfigurationChanged(r.activity, r.newConfig);
2495 r.newConfig = null;
2496 }
2497 } else {
2498 if (r.activity.mVisibleFromServer) {
2499 r.activity.mVisibleFromServer = false;
2500 mNumVisibleActivities--;
2501 v.setVisibility(View.INVISIBLE);
2502 }
2503 }
2504 }
2505 }
2506
2507 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002508 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 r.activity.mConfigChangeFlags |= configChanges;
2510
2511 StopInfo info = new StopInfo();
2512 performStopActivityInner(r, info, show);
2513
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002514 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 TAG, "Finishing stop of " + r + ": show=" + show
2516 + " win=" + r.window);
2517
2518 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 // Tell activity manager we have been stopped.
2521 try {
2522 ActivityManagerNative.getDefault().activityStopped(
2523 r.token, info.thumbnail, info.description);
2524 } catch (RemoteException ex) {
2525 }
2526 }
2527
2528 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002529 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 if (r.stopped) {
2531 r.activity.performRestart();
2532 r.stopped = false;
2533 }
2534 }
2535
2536 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002537 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 if (!show && !r.stopped) {
2539 performStopActivityInner(r, null, show);
2540 } else if (show && r.stopped) {
2541 // If we are getting ready to gc after going to the background, well
2542 // we are back active so skip it.
2543 unscheduleGcIdler();
2544
2545 r.activity.performRestart();
2546 r.stopped = false;
2547 }
2548 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002549 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 TAG, "Handle window " + r + " visibility: " + show);
2551 updateVisibility(r, show);
2552 }
2553 }
2554
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002555 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 final int N = results.size();
2557 for (int i=0; i<N; i++) {
2558 ResultInfo ri = results.get(i);
2559 try {
2560 if (ri.mData != null) {
2561 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2562 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002563 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002564 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 r.activity.dispatchActivityResult(ri.mResultWho,
2566 ri.mRequestCode, ri.mResultCode, ri.mData);
2567 } catch (Exception e) {
2568 if (!mInstrumentation.onException(r.activity, e)) {
2569 throw new RuntimeException(
2570 "Failure delivering result " + ri + " to activity "
2571 + r.intent.getComponent().toShortString()
2572 + ": " + e.toString(), e);
2573 }
2574 }
2575 }
2576 }
2577
2578 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002579 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002580 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 if (r != null) {
2582 final boolean resumed = !r.paused;
2583 if (!r.activity.mFinished && r.activity.mDecor != null
2584 && r.hideForNow && resumed) {
2585 // We had hidden the activity because it started another
2586 // one... we have gotten a result back and we are not
2587 // paused, so make sure our window is visible.
2588 updateVisibility(r, true);
2589 }
2590 if (resumed) {
2591 try {
2592 // Now we are idle.
2593 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002594 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 mInstrumentation.callActivityOnPause(r.activity);
2596 if (!r.activity.mCalled) {
2597 throw new SuperNotCalledException(
2598 "Activity " + r.intent.getComponent().toShortString()
2599 + " did not call through to super.onPause()");
2600 }
2601 } catch (SuperNotCalledException e) {
2602 throw e;
2603 } catch (Exception e) {
2604 if (!mInstrumentation.onException(r.activity, e)) {
2605 throw new RuntimeException(
2606 "Unable to pause activity "
2607 + r.intent.getComponent().toShortString()
2608 + ": " + e.toString(), e);
2609 }
2610 }
2611 }
2612 deliverResults(r, res.results);
2613 if (resumed) {
2614 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002615 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 }
2617 }
2618 }
2619
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002620 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 return performDestroyActivity(token, finishing, 0, false);
2622 }
2623
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002624 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002626 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002627 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 if (r != null) {
2629 r.activity.mConfigChangeFlags |= configChanges;
2630 if (finishing) {
2631 r.activity.mFinished = true;
2632 }
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05002633 if (getNonConfigInstance) {
2634 r.activity.mChangingConfigurations = true;
2635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 if (!r.paused) {
2637 try {
2638 r.activity.mCalled = false;
2639 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002640 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 r.activity.getComponentName().getClassName());
2642 if (!r.activity.mCalled) {
2643 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002644 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 + " did not call through to super.onPause()");
2646 }
2647 } catch (SuperNotCalledException e) {
2648 throw e;
2649 } catch (Exception e) {
2650 if (!mInstrumentation.onException(r.activity, e)) {
2651 throw new RuntimeException(
2652 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002653 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 + ": " + e.toString(), e);
2655 }
2656 }
2657 r.paused = true;
2658 }
2659 if (!r.stopped) {
2660 try {
2661 r.activity.performStop();
2662 } catch (SuperNotCalledException e) {
2663 throw e;
2664 } catch (Exception e) {
2665 if (!mInstrumentation.onException(r.activity, e)) {
2666 throw new RuntimeException(
2667 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002668 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 + ": " + e.toString(), e);
2670 }
2671 }
2672 r.stopped = true;
2673 }
2674 if (getNonConfigInstance) {
2675 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002676 r.lastNonConfigurationInstances
2677 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 } catch (Exception e) {
2679 if (!mInstrumentation.onException(r.activity, e)) {
2680 throw new RuntimeException(
2681 "Unable to retain activity "
2682 + r.intent.getComponent().toShortString()
2683 + ": " + e.toString(), e);
2684 }
2685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 }
2687 try {
2688 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002689 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 if (!r.activity.mCalled) {
2691 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002692 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 " did not call through to super.onDestroy()");
2694 }
2695 if (r.window != null) {
2696 r.window.closeAllPanels();
2697 }
2698 } catch (SuperNotCalledException e) {
2699 throw e;
2700 } catch (Exception e) {
2701 if (!mInstrumentation.onException(r.activity, e)) {
2702 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002703 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2704 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 }
2706 }
2707 }
2708 mActivities.remove(token);
2709
2710 return r;
2711 }
2712
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002713 private static String safeToComponentShortString(Intent intent) {
2714 ComponentName component = intent.getComponent();
2715 return component == null ? "[Unknown]" : component.toShortString();
2716 }
2717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 private final void handleDestroyActivity(IBinder token, boolean finishing,
2719 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002720 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 configChanges, getNonConfigInstance);
2722 if (r != null) {
2723 WindowManager wm = r.activity.getWindowManager();
2724 View v = r.activity.mDecor;
2725 if (v != null) {
2726 if (r.activity.mVisibleFromServer) {
2727 mNumVisibleActivities--;
2728 }
2729 IBinder wtoken = v.getWindowToken();
2730 if (r.activity.mWindowAdded) {
2731 wm.removeViewImmediate(v);
2732 }
2733 if (wtoken != null) {
2734 WindowManagerImpl.getDefault().closeAll(wtoken,
2735 r.activity.getClass().getName(), "Activity");
2736 }
2737 r.activity.mDecor = null;
2738 }
2739 WindowManagerImpl.getDefault().closeAll(token,
2740 r.activity.getClass().getName(), "Activity");
2741
2742 // Mocked out contexts won't be participating in the normal
2743 // process lifecycle, but if we're running with a proper
2744 // ApplicationContext we need to have it tear down things
2745 // cleanly.
2746 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002747 if (c instanceof ContextImpl) {
2748 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 r.activity.getClass().getName(), "Activity");
2750 }
2751 }
2752 if (finishing) {
2753 try {
2754 ActivityManagerNative.getDefault().activityDestroyed(token);
2755 } catch (RemoteException ex) {
2756 // If the system process has died, it's game over for everyone.
2757 }
2758 }
2759 }
2760
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002761 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 // If we are getting ready to gc after going to the background, well
2763 // we are back active so skip it.
2764 unscheduleGcIdler();
2765
2766 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002767
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002768 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002769 + tmp.token + " with configChanges=0x"
2770 + Integer.toHexString(configChanges));
2771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 // First: make sure we have the most recent configuration and most
2773 // recent version of the activity, or skip it if some previous call
2774 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002775 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 int N = mRelaunchingActivities.size();
2777 IBinder token = tmp.token;
2778 tmp = null;
2779 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002780 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 if (r.token == token) {
2782 tmp = r;
2783 mRelaunchingActivities.remove(i);
2784 i--;
2785 N--;
2786 }
2787 }
Bob Leee5408332009-09-04 18:31:17 -07002788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002790 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 return;
2792 }
Bob Leee5408332009-09-04 18:31:17 -07002793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 if (mPendingConfiguration != null) {
2795 changedConfig = mPendingConfiguration;
2796 mPendingConfiguration = null;
2797 }
2798 }
Bob Leee5408332009-09-04 18:31:17 -07002799
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002800 if (tmp.createdConfig != null) {
2801 // If the activity manager is passing us its current config,
2802 // assume that is really what we want regardless of what we
2803 // may have pending.
2804 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002805 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2806 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2807 if (changedConfig == null
2808 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2809 changedConfig = tmp.createdConfig;
2810 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002811 }
2812 }
2813
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002814 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002815 + tmp.token + ": changedConfig=" + changedConfig);
2816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 // If there was a pending configuration change, execute it first.
2818 if (changedConfig != null) {
2819 handleConfigurationChanged(changedConfig);
2820 }
Bob Leee5408332009-09-04 18:31:17 -07002821
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002822 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002823 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 if (r == null) {
2825 return;
2826 }
Bob Leee5408332009-09-04 18:31:17 -07002827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002829 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 Bundle savedState = null;
2832 if (!r.paused) {
2833 savedState = performPauseActivity(r.token, false, true);
2834 }
Bob Leee5408332009-09-04 18:31:17 -07002835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 r.activity = null;
2839 r.window = null;
2840 r.hideForNow = false;
2841 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002842 // Merge any pending results and pending intents; don't just replace them
2843 if (tmp.pendingResults != null) {
2844 if (r.pendingResults == null) {
2845 r.pendingResults = tmp.pendingResults;
2846 } else {
2847 r.pendingResults.addAll(tmp.pendingResults);
2848 }
2849 }
2850 if (tmp.pendingIntents != null) {
2851 if (r.pendingIntents == null) {
2852 r.pendingIntents = tmp.pendingIntents;
2853 } else {
2854 r.pendingIntents.addAll(tmp.pendingIntents);
2855 }
2856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 r.startsNotResumed = tmp.startsNotResumed;
2858 if (savedState != null) {
2859 r.state = savedState;
2860 }
Bob Leee5408332009-09-04 18:31:17 -07002861
Christopher Tateb70f3df2009-04-07 16:07:59 -07002862 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 }
2864
2865 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002866 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 Bitmap thumbnail = createThumbnailBitmap(r);
2868 CharSequence description = null;
2869 try {
2870 description = r.activity.onCreateDescription();
2871 } catch (Exception e) {
2872 if (!mInstrumentation.onException(r.activity, e)) {
2873 throw new RuntimeException(
2874 "Unable to create description of activity "
2875 + r.intent.getComponent().toShortString()
2876 + ": " + e.toString(), e);
2877 }
2878 }
2879 //System.out.println("Reporting top thumbnail " + thumbnail);
2880 try {
2881 ActivityManagerNative.getDefault().reportThumbnail(
2882 token, thumbnail, description);
2883 } catch (RemoteException ex) {
2884 }
2885 }
2886
2887 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2888 boolean allActivities, Configuration newConfig) {
2889 ArrayList<ComponentCallbacks> callbacks
2890 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002893 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002895 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 Activity a = ar.activity;
2897 if (a != null) {
2898 if (!ar.activity.mFinished && (allActivities ||
2899 (a != null && !ar.paused))) {
2900 // If the activity is currently resumed, its configuration
2901 // needs to change right now.
2902 callbacks.add(a);
2903 } else if (newConfig != null) {
2904 // Otherwise, we will tell it about the change
2905 // the next time it is resumed or shown. Note that
2906 // the activity manager may, before then, decide the
2907 // activity needs to be destroyed to handle its new
2908 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002909 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002910 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 ar.newConfig = newConfig;
2912 }
2913 }
2914 }
2915 }
2916 if (mServices.size() > 0) {
2917 Iterator<Service> it = mServices.values().iterator();
2918 while (it.hasNext()) {
2919 callbacks.add(it.next());
2920 }
2921 }
2922 synchronized (mProviderMap) {
2923 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002924 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 while (it.hasNext()) {
2926 callbacks.add(it.next().mLocalProvider);
2927 }
2928 }
2929 }
2930 final int N = mAllApplications.size();
2931 for (int i=0; i<N; i++) {
2932 callbacks.add(mAllApplications.get(i));
2933 }
Bob Leee5408332009-09-04 18:31:17 -07002934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 return callbacks;
2936 }
Bob Leee5408332009-09-04 18:31:17 -07002937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 private final void performConfigurationChanged(
2939 ComponentCallbacks cb, Configuration config) {
2940 // Only for Activity objects, check that they actually call up to their
2941 // superclass implementation. ComponentCallbacks is an interface, so
2942 // we check the runtime type and act accordingly.
2943 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2944 if (activity != null) {
2945 activity.mCalled = false;
2946 }
Bob Leee5408332009-09-04 18:31:17 -07002947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 boolean shouldChangeConfig = false;
2949 if ((activity == null) || (activity.mCurrentConfig == null)) {
2950 shouldChangeConfig = true;
2951 } else {
Bob Leee5408332009-09-04 18:31:17 -07002952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 // If the new config is the same as the config this Activity
2954 // is already running with then don't bother calling
2955 // onConfigurationChanged
2956 int diff = activity.mCurrentConfig.diff(config);
2957 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 // If this activity doesn't handle any of the config changes
2960 // then don't bother calling onConfigurationChanged as we're
2961 // going to destroy it.
2962 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2963 shouldChangeConfig = true;
2964 }
2965 }
2966 }
Bob Leee5408332009-09-04 18:31:17 -07002967
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002968 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002969 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 if (shouldChangeConfig) {
2971 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 if (activity != null) {
2974 if (!activity.mCalled) {
2975 throw new SuperNotCalledException(
2976 "Activity " + activity.getLocalClassName() +
2977 " did not call through to super.onConfigurationChanged()");
2978 }
2979 activity.mConfigChangeFlags = 0;
2980 activity.mCurrentConfig = new Configuration(config);
2981 }
2982 }
2983 }
2984
Dianne Hackbornae078162010-03-18 11:29:37 -07002985 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002986 if (mResConfiguration == null) {
2987 mResConfiguration = new Configuration();
2988 }
2989 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002990 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002991 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002992 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002993 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002994 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002995 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002996
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002997 // set it for java, this also affects newly created Resources
2998 if (config.locale != null) {
2999 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 }
Bob Leee5408332009-09-04 18:31:17 -07003001
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003002 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07003003
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003004 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003005 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003006
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003007 Iterator<WeakReference<Resources>> it =
3008 mActiveResources.values().iterator();
3009 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3010 // mActiveResources.entrySet().iterator();
3011 while (it.hasNext()) {
3012 WeakReference<Resources> v = it.next();
3013 Resources r = v.get();
3014 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003015 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003016 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003017 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003018 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003019 // + " " + r + ": " + r.getConfiguration());
3020 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003021 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003022 it.remove();
3023 }
3024 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003025
3026 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003027 }
3028
3029 final void handleConfigurationChanged(Configuration config) {
3030
3031 ArrayList<ComponentCallbacks> callbacks = null;
3032
3033 synchronized (mPackages) {
3034 if (mPendingConfiguration != null) {
3035 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3036 config = mPendingConfiguration;
3037 }
3038 mPendingConfiguration = null;
3039 }
3040
3041 if (config == null) {
3042 return;
3043 }
3044
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003045 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003046 + config);
3047
3048 applyConfigurationToResourcesLocked(config);
3049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 if (mConfiguration == null) {
3051 mConfiguration = new Configuration();
3052 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003053 if (!mConfiguration.isOtherSeqNewer(config)) {
3054 return;
3055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 callbacks = collectComponentCallbacksLocked(false, config);
3059 }
Bob Leee5408332009-09-04 18:31:17 -07003060
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003061 if (callbacks != null) {
3062 final int N = callbacks.size();
3063 for (int i=0; i<N; i++) {
3064 performConfigurationChanged(callbacks.get(i), config);
3065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 }
3067 }
3068
3069 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003070 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 if (r == null || r.activity == null) {
3072 return;
3073 }
Bob Leee5408332009-09-04 18:31:17 -07003074
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003075 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003076 + r.activityInfo.name);
3077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 performConfigurationChanged(r.activity, mConfiguration);
3079 }
3080
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003081 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003082 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003083 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003084 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3085 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003086 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003087 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003088 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003089 } finally {
3090 try {
3091 pcd.fd.close();
3092 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003093 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003094 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003095 }
3096 } else {
3097 Debug.stopMethodTracing();
3098 }
3099 }
Bob Leee5408332009-09-04 18:31:17 -07003100
Andy McFadden824c5102010-07-09 16:26:57 -07003101 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3102 if (managed) {
3103 try {
3104 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3105 } catch (IOException e) {
3106 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3107 + " -- can the process access this path?");
3108 } finally {
3109 try {
3110 dhd.fd.close();
3111 } catch (IOException e) {
3112 Slog.w(TAG, "Failure closing profile fd", e);
3113 }
3114 }
3115 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003116 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003117 }
3118 }
3119
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003120 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3121 boolean hasPkgInfo = false;
3122 if (packages != null) {
3123 for (int i=packages.length-1; i>=0; i--) {
3124 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3125 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003126 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003127 ref = mPackages.get(packages[i]);
3128 if (ref != null && ref.get() != null) {
3129 hasPkgInfo = true;
3130 } else {
3131 ref = mResourcePackages.get(packages[i]);
3132 if (ref != null && ref.get() != null) {
3133 hasPkgInfo = true;
3134 }
3135 }
3136 }
3137 mPackages.remove(packages[i]);
3138 mResourcePackages.remove(packages[i]);
3139 }
3140 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003141 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003142 hasPkgInfo);
3143 }
3144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 final void handleLowMemory() {
3146 ArrayList<ComponentCallbacks> callbacks
3147 = new ArrayList<ComponentCallbacks>();
3148
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003149 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 callbacks = collectComponentCallbacksLocked(true, null);
3151 }
Bob Leee5408332009-09-04 18:31:17 -07003152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 final int N = callbacks.size();
3154 for (int i=0; i<N; i++) {
3155 callbacks.get(i).onLowMemory();
3156 }
3157
Chris Tatece229052009-03-25 16:44:52 -07003158 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3159 if (Process.myUid() != Process.SYSTEM_UID) {
3160 int sqliteReleased = SQLiteDatabase.releaseMemory();
3161 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3162 }
Bob Leee5408332009-09-04 18:31:17 -07003163
Mike Reedcaf0df12009-04-27 14:32:05 -04003164 // Ask graphics to free up as much as possible (font/image caches)
3165 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166
3167 BinderInternal.forceGc("mem");
3168 }
3169
3170 private final void handleBindApplication(AppBindData data) {
3171 mBoundApplication = data;
3172 mConfiguration = new Configuration(data.config);
3173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003175 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 android.ddm.DdmHandleAppName.setAppName(data.processName);
3177
3178 /*
3179 * Before spawning a new process, reset the time zone to be the system time zone.
3180 * This needs to be done because the system time zone could have changed after the
3181 * the spawning of this process. Without doing this this process would have the incorrect
3182 * system time zone.
3183 */
3184 TimeZone.setDefault(null);
3185
3186 /*
3187 * Initialize the default locale in this process for the reasons we set the time zone.
3188 */
3189 Locale.setDefault(data.config.locale);
3190
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003191 /*
3192 * Update the system configuration since its preloaded and might not
3193 * reflect configuration changes. The configuration object passed
3194 * in AppBindData can be safely assumed to be up to date
3195 */
3196 Resources.getSystem().updateConfiguration(mConfiguration, null);
3197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 data.info = getPackageInfoNoCheck(data.appInfo);
3199
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003200 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003201 * For system applications on userdebug/eng builds, log stack
3202 * traces of disk and network access to dropbox for analysis.
3203 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003204 if ((data.appInfo.flags &
3205 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003206 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3207 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003208 }
3209
3210 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003211 * For apps targetting SDK Honeycomb or later, we don't allow
3212 * network usage on the main event loop / UI thread.
3213 *
3214 * Note to those grepping: this is what ultimately throws
3215 * NetworkOnMainThreadException ...
3216 */
3217 if (data.appInfo.targetSdkVersion > 9) {
3218 StrictMode.enableDeathOnNetwork();
3219 }
3220
3221 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003222 * Switch this process to density compatibility mode if needed.
3223 */
3224 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3225 == 0) {
3226 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3227 }
Bob Leee5408332009-09-04 18:31:17 -07003228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3230 // XXX should have option to change the port.
3231 Debug.changeDebugPort(8100);
3232 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003233 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 + " is waiting for the debugger on port 8100...");
3235
3236 IActivityManager mgr = ActivityManagerNative.getDefault();
3237 try {
3238 mgr.showWaitingForDebugger(mAppThread, true);
3239 } catch (RemoteException ex) {
3240 }
3241
3242 Debug.waitForDebugger();
3243
3244 try {
3245 mgr.showWaitingForDebugger(mAppThread, false);
3246 } catch (RemoteException ex) {
3247 }
3248
3249 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003250 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 + " can be debugged on port 8100...");
3252 }
3253 }
3254
3255 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003256 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 appContext.init(data.info, null, this);
3258 InstrumentationInfo ii = null;
3259 try {
3260 ii = appContext.getPackageManager().
3261 getInstrumentationInfo(data.instrumentationName, 0);
3262 } catch (PackageManager.NameNotFoundException e) {
3263 }
3264 if (ii == null) {
3265 throw new RuntimeException(
3266 "Unable to find instrumentation info for: "
3267 + data.instrumentationName);
3268 }
3269
3270 mInstrumentationAppDir = ii.sourceDir;
3271 mInstrumentationAppPackage = ii.packageName;
3272 mInstrumentedAppDir = data.info.getAppDir();
3273
3274 ApplicationInfo instrApp = new ApplicationInfo();
3275 instrApp.packageName = ii.packageName;
3276 instrApp.sourceDir = ii.sourceDir;
3277 instrApp.publicSourceDir = ii.publicSourceDir;
3278 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003279 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003280 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003282 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 instrContext.init(pi, null, this);
3284
3285 try {
3286 java.lang.ClassLoader cl = instrContext.getClassLoader();
3287 mInstrumentation = (Instrumentation)
3288 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3289 } catch (Exception e) {
3290 throw new RuntimeException(
3291 "Unable to instantiate instrumentation "
3292 + data.instrumentationName + ": " + e.toString(), e);
3293 }
3294
3295 mInstrumentation.init(this, instrContext, appContext,
3296 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3297
3298 if (data.profileFile != null && !ii.handleProfiling) {
3299 data.handlingProfiling = true;
3300 File file = new File(data.profileFile);
3301 file.getParentFile().mkdirs();
3302 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3303 }
3304
3305 try {
3306 mInstrumentation.onCreate(data.instrumentationArgs);
3307 }
3308 catch (Exception e) {
3309 throw new RuntimeException(
3310 "Exception thrown in onCreate() of "
3311 + data.instrumentationName + ": " + e.toString(), e);
3312 }
3313
3314 } else {
3315 mInstrumentation = new Instrumentation();
3316 }
3317
Christopher Tate181fafa2009-05-14 11:12:14 -07003318 // If the app is being launched for full backup or restore, bring it up in
3319 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003320 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 mInitialApplication = app;
3322
3323 List<ProviderInfo> providers = data.providers;
3324 if (providers != null) {
3325 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003326 // For process that contain content providers, we want to
3327 // ensure that the JIT is enabled "at some point".
3328 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
3330
3331 try {
3332 mInstrumentation.callApplicationOnCreate(app);
3333 } catch (Exception e) {
3334 if (!mInstrumentation.onException(app, e)) {
3335 throw new RuntimeException(
3336 "Unable to create application " + app.getClass().getName()
3337 + ": " + e.toString(), e);
3338 }
3339 }
3340 }
3341
3342 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3343 IActivityManager am = ActivityManagerNative.getDefault();
3344 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3345 Debug.stopMethodTracing();
3346 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003347 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 // + ", app thr: " + mAppThread);
3349 try {
3350 am.finishInstrumentation(mAppThread, resultCode, results);
3351 } catch (RemoteException ex) {
3352 }
3353 }
3354
3355 private final void installContentProviders(
3356 Context context, List<ProviderInfo> providers) {
3357 final ArrayList<IActivityManager.ContentProviderHolder> results =
3358 new ArrayList<IActivityManager.ContentProviderHolder>();
3359
3360 Iterator<ProviderInfo> i = providers.iterator();
3361 while (i.hasNext()) {
3362 ProviderInfo cpi = i.next();
3363 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003364 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 buf.append(cpi.authority);
3366 buf.append(": ");
3367 buf.append(cpi.name);
3368 Log.i(TAG, buf.toString());
3369 IContentProvider cp = installProvider(context, null, cpi, false);
3370 if (cp != null) {
3371 IActivityManager.ContentProviderHolder cph =
3372 new IActivityManager.ContentProviderHolder(cpi);
3373 cph.provider = cp;
3374 results.add(cph);
3375 // Don't ever unload this provider from the process.
3376 synchronized(mProviderMap) {
3377 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3378 }
3379 }
3380 }
3381
3382 try {
3383 ActivityManagerNative.getDefault().publishContentProviders(
3384 getApplicationThread(), results);
3385 } catch (RemoteException ex) {
3386 }
3387 }
3388
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003389 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003391 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 if (pr != null) {
3393 return pr.mProvider;
3394 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003395 return null;
3396 }
3397 }
3398
3399 private final IContentProvider getProvider(Context context, String name) {
3400 IContentProvider existing = getExistingProvider(context, name);
3401 if (existing != null) {
3402 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 }
3404
3405 IActivityManager.ContentProviderHolder holder = null;
3406 try {
3407 holder = ActivityManagerNative.getDefault().getContentProvider(
3408 getApplicationThread(), name);
3409 } catch (RemoteException ex) {
3410 }
3411 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003412 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 return null;
3414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415
3416 IContentProvider prov = installProvider(context, holder.provider,
3417 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003418 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 if (holder.noReleaseNeeded || holder.provider == null) {
3420 // We are not going to release the provider if it is an external
3421 // provider that doesn't care about being released, or if it is
3422 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003423 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 synchronized(mProviderMap) {
3425 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3426 }
3427 }
3428 return prov;
3429 }
3430
3431 public final IContentProvider acquireProvider(Context c, String name) {
3432 IContentProvider provider = getProvider(c, name);
3433 if(provider == null)
3434 return null;
3435 IBinder jBinder = provider.asBinder();
3436 synchronized(mProviderMap) {
3437 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3438 if(prc == null) {
3439 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3440 } else {
3441 prc.count++;
3442 } //end else
3443 } //end synchronized
3444 return provider;
3445 }
3446
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003447 public final IContentProvider acquireExistingProvider(Context c, String name) {
3448 IContentProvider provider = getExistingProvider(c, name);
3449 if(provider == null)
3450 return null;
3451 IBinder jBinder = provider.asBinder();
3452 synchronized(mProviderMap) {
3453 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3454 if(prc == null) {
3455 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3456 } else {
3457 prc.count++;
3458 } //end else
3459 } //end synchronized
3460 return provider;
3461 }
3462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 public final boolean releaseProvider(IContentProvider provider) {
3464 if(provider == null) {
3465 return false;
3466 }
3467 IBinder jBinder = provider.asBinder();
3468 synchronized(mProviderMap) {
3469 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3470 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003471 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 return false;
3473 } else {
3474 prc.count--;
3475 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003476 // Schedule the actual remove asynchronously, since we
3477 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003478 // TODO: it would be nice to post a delayed message, so
3479 // if we come back and need the same provider quickly
3480 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003481 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3482 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 } //end if
3484 } //end else
3485 } //end synchronized
3486 return true;
3487 }
3488
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003489 final void completeRemoveProvider(IContentProvider provider) {
3490 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003491 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003492 synchronized(mProviderMap) {
3493 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3494 if(prc != null && prc.count == 0) {
3495 mProviderRefCountMap.remove(jBinder);
3496 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003497 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003498 }
3499 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003500
3501 if (name != null) {
3502 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003503 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003504 "ActivityManagerNative.removeContentProvider(" + name);
3505 ActivityManagerNative.getDefault().removeContentProvider(
3506 getApplicationThread(), name);
3507 } catch (RemoteException e) {
3508 //do nothing content provider object is dead any way
3509 } //end catch
3510 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003511 }
3512
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003513 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003515 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 }
3517 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003519 String name = null;
3520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003522 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003524 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 IBinder myBinder = pr.mProvider.asBinder();
3526 if (myBinder == providerBinder) {
3527 //find if its published by this process itself
3528 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003529 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003530 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003532 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 "death recipient");
3534 //content provider is in another process
3535 myBinder.unlinkToDeath(pr, 0);
3536 iter.remove();
3537 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003538 if(name == null) {
3539 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 }
3541 } //end if myBinder
3542 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003543
3544 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 }
3546
3547 final void removeDeadProvider(String name, IContentProvider provider) {
3548 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003549 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003551 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003552 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003553 if (removed != null) {
3554 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 }
3557 }
3558 }
3559
3560 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003561 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003563 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003564 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003565 if (removed != null) {
3566 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 }
3569 }
3570
3571 private final IContentProvider installProvider(Context context,
3572 IContentProvider provider, ProviderInfo info, boolean noisy) {
3573 ContentProvider localProvider = null;
3574 if (provider == null) {
3575 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003576 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 + info.name);
3578 }
3579 Context c = null;
3580 ApplicationInfo ai = info.applicationInfo;
3581 if (context.getPackageName().equals(ai.packageName)) {
3582 c = context;
3583 } else if (mInitialApplication != null &&
3584 mInitialApplication.getPackageName().equals(ai.packageName)) {
3585 c = mInitialApplication;
3586 } else {
3587 try {
3588 c = context.createPackageContext(ai.packageName,
3589 Context.CONTEXT_INCLUDE_CODE);
3590 } catch (PackageManager.NameNotFoundException e) {
3591 }
3592 }
3593 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003594 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 ai.packageName +
3596 " while loading content provider " +
3597 info.name);
3598 return null;
3599 }
3600 try {
3601 final java.lang.ClassLoader cl = c.getClassLoader();
3602 localProvider = (ContentProvider)cl.
3603 loadClass(info.name).newInstance();
3604 provider = localProvider.getIContentProvider();
3605 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003606 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 info.name + " from sourceDir " +
3608 info.applicationInfo.sourceDir);
3609 return null;
3610 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003611 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 TAG, "Instantiating local provider " + info.name);
3613 // XXX Need to create the correct context for this provider.
3614 localProvider.attachInfo(c, info);
3615 } catch (java.lang.Exception e) {
3616 if (!mInstrumentation.onException(null, e)) {
3617 throw new RuntimeException(
3618 "Unable to get provider " + info.name
3619 + ": " + e.toString(), e);
3620 }
3621 return null;
3622 }
3623 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003624 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 + info.name);
3626 }
3627
3628 synchronized (mProviderMap) {
3629 // Cache the pointer for the remote provider.
3630 String names[] = PATTERN_SEMICOLON.split(info.authority);
3631 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003632 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 localProvider);
3634 try {
3635 provider.asBinder().linkToDeath(pr, 0);
3636 mProviderMap.put(names[i], pr);
3637 } catch (RemoteException e) {
3638 return null;
3639 }
3640 }
3641 if (localProvider != null) {
3642 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003643 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 }
3645 }
3646
3647 return provider;
3648 }
3649
3650 private final void attach(boolean system) {
3651 sThreadLocal.set(this);
3652 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003654 ViewRoot.addFirstDrawHandler(new Runnable() {
3655 public void run() {
3656 ensureJitEnabled();
3657 }
3658 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3660 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3661 IActivityManager mgr = ActivityManagerNative.getDefault();
3662 try {
3663 mgr.attachApplication(mAppThread);
3664 } catch (RemoteException ex) {
3665 }
3666 } else {
3667 // Don't set application object here -- if the system crashes,
3668 // we can't display an alert, we just want to die die die.
3669 android.ddm.DdmHandleAppName.setAppName("system_process");
3670 try {
3671 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003672 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 context.init(getSystemContext().mPackageInfo, null, this);
3674 Application app = Instrumentation.newApplication(Application.class, context);
3675 mAllApplications.add(app);
3676 mInitialApplication = app;
3677 app.onCreate();
3678 } catch (Exception e) {
3679 throw new RuntimeException(
3680 "Unable to instantiate Application():" + e.toString(), e);
3681 }
3682 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003683
3684 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3685 public void onConfigurationChanged(Configuration newConfig) {
3686 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003687 // We need to apply this change to the resources
3688 // immediately, because upon returning the view
3689 // hierarchy will be informed about it.
3690 if (applyConfigurationToResourcesLocked(newConfig)) {
3691 // This actually changed the resources! Tell
3692 // everyone about it.
3693 if (mPendingConfiguration == null ||
3694 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3695 mPendingConfiguration = newConfig;
3696
3697 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3698 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003699 }
3700 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003701 }
3702 public void onLowMemory() {
3703 }
3704 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 }
3706
3707 private final void detach()
3708 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 sThreadLocal.set(null);
3710 }
3711
3712 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003713 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 ActivityThread thread = new ActivityThread();
3715 thread.attach(true);
3716 return thread;
3717 }
3718
3719 public final void installSystemProviders(List providers) {
3720 if (providers != null) {
3721 installContentProviders(mInitialApplication,
3722 (List<ProviderInfo>)providers);
3723 }
3724 }
3725
3726 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003727 SamplingProfilerIntegration.start();
3728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 Process.setArgV0("<pre-initialized>");
3730
3731 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003732 if (sMainThreadHandler == null) {
3733 sMainThreadHandler = new Handler();
3734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735
3736 ActivityThread thread = new ActivityThread();
3737 thread.attach(false);
3738
Dianne Hackborn287952c2010-09-22 22:34:31 -07003739 if (false) {
3740 Looper.myLooper().setMessageLogging(new
3741 LogPrinter(Log.DEBUG, "ActivityThread"));
3742 }
3743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 Looper.loop();
3745
3746 if (Process.supportsProcesses()) {
3747 throw new RuntimeException("Main thread loop unexpectedly exited");
3748 }
3749
3750 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003751 String name = (thread.mInitialApplication != null)
3752 ? thread.mInitialApplication.getPackageName()
3753 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003754 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 }
3756}