blob: 0c761fc4b7e3b1d641ca82176824e2f7bbd32f87 [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;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070021import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import 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;
Robert Greenwalt434203a2010-10-11 16:00:27 -070045import android.net.IConnectivityManager;
46import android.net.Proxy;
47import android.net.ProxyProperties;
Romain Guya9582652011-11-10 14:20:10 -080048import android.opengl.GLUtils;
Joe Onoratod630f102011-03-17 18:42:26 -070049import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.Bundle;
51import android.os.Debug;
52import android.os.Handler;
53import android.os.IBinder;
54import android.os.Looper;
55import android.os.Message;
56import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070057import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.Process;
59import android.os.RemoteException;
60import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070061import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.SystemClock;
63import android.util.AndroidRuntimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.util.DisplayMetrics;
65import android.util.EventLog;
66import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -070067import android.util.LogPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080068import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.view.Display;
Romain Guy52339202010-09-03 16:04:46 -070070import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.view.View;
72import android.view.ViewDebug;
73import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -070074import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.view.Window;
76import android.view.WindowManager;
77import android.view.WindowManagerImpl;
78
79import com.android.internal.os.BinderInternal;
80import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070081import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
83import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
84
85import java.io.File;
86import java.io.FileDescriptor;
87import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070088import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import java.io.PrintWriter;
90import java.lang.ref.WeakReference;
Robert Greenwalt03595d02010-11-02 14:08:23 -070091import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import java.util.ArrayList;
93import java.util.HashMap;
94import java.util.Iterator;
95import java.util.List;
96import java.util.Locale;
97import java.util.Map;
98import java.util.TimeZone;
99import java.util.regex.Pattern;
100
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -0800101import dalvik.system.CloseGuard;
Bob Leee5408332009-09-04 18:31:17 -0700102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103final class SuperNotCalledException extends AndroidRuntimeException {
104 public SuperNotCalledException(String msg) {
105 super(msg);
106 }
107}
108
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700109final class RemoteServiceException extends AndroidRuntimeException {
110 public RemoteServiceException(String msg) {
111 super(msg);
112 }
113}
114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115/**
116 * This manages the execution of the main thread in an
117 * application process, scheduling and executing activities,
118 * broadcasts, and other operations on it as the activity
119 * manager requests.
120 *
121 * {@hide}
122 */
123public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700124 /** @hide */
125 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700126 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700127 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700128 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700129 /** @hide */
130 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700131 private static final boolean DEBUG_RESULTS = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700132 private static final boolean DEBUG_BACKUP = true;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700133 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
135 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
136 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
137 private static final int LOG_ON_PAUSE_CALLED = 30021;
138 private static final int LOG_ON_RESUME_CALLED = 30022;
139
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700140 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700141
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700142 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700144 final ApplicationThread mAppThread = new ApplicationThread();
145 final Looper mLooper = Looper.myLooper();
146 final H mH = new H();
147 final HashMap<IBinder, ActivityClientRecord> mActivities
148 = new HashMap<IBinder, ActivityClientRecord>();
149 // List of new activities (via ActivityRecord.nextIdle) that should
150 // be reported when next we idle.
151 ActivityClientRecord mNewActivities = null;
152 // Number of activities that are currently visible on-screen.
153 int mNumVisibleActivities = 0;
154 final HashMap<IBinder, Service> mServices
155 = new HashMap<IBinder, Service>();
156 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700157 Profiler mProfiler;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700158 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700159 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700160 Configuration mResConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700161 CompatibilityInfo mResCompatibilityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700162 Application mInitialApplication;
163 final ArrayList<Application> mAllApplications
164 = new ArrayList<Application>();
165 // set of instantiated backup agents, keyed by package name
166 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Romain Guy65b345f2011-07-27 18:51:50 -0700167 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal<ActivityThread>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700168 Instrumentation mInstrumentation;
169 String mInstrumentationAppDir = null;
170 String mInstrumentationAppPackage = null;
171 String mInstrumentedAppDir = null;
172 boolean mSystemThread = false;
173 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700175 // These can be accessed by multiple threads; mPackages is the lock.
176 // XXX For now we keep around information about all packages we have
177 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800178 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700179 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800180 // which means this lock gets held while the activity and window managers
181 // holds their own lock. Thus you MUST NEVER call back into the activity manager
182 // or window manager or anything that depends on them while holding this lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700183 final HashMap<String, WeakReference<LoadedApk>> mPackages
184 = new HashMap<String, WeakReference<LoadedApk>>();
185 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
186 = new HashMap<String, WeakReference<LoadedApk>>();
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700187 final HashMap<CompatibilityInfo, DisplayMetrics> mDisplayMetrics
188 = new HashMap<CompatibilityInfo, DisplayMetrics>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700189 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
190 = new HashMap<ResourcesKey, WeakReference<Resources> >();
191 final ArrayList<ActivityClientRecord> mRelaunchingActivities
192 = new ArrayList<ActivityClientRecord>();
193 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700195 // The lock of mProviderMap protects the following variables.
196 final HashMap<String, ProviderClientRecord> mProviderMap
197 = new HashMap<String, ProviderClientRecord>();
198 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
199 = new HashMap<IBinder, ProviderRefCount>();
200 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
201 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
Jeff Hamilton52d32032011-01-08 15:31:26 -0600203 final HashMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
204 = new HashMap<Activity, ArrayList<OnActivityPausedListener>>();
205
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700206 final GcIdler mGcIdler = new GcIdler();
207 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700209 static Handler sMainThreadHandler; // set once in main()
210
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800211 Bundle mCoreSettings = null;
212
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400213 static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700215 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 Intent intent;
217 Bundle state;
218 Activity activity;
219 Window window;
220 Activity parent;
221 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700222 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 boolean paused;
224 boolean stopped;
225 boolean hideForNow;
226 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700227 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700228 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700230 String profileFile;
231 ParcelFileDescriptor profileFd;
232 boolean autoStopProfiler;
233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400235 CompatibilityInfo compatInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700236 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 List<ResultInfo> pendingResults;
239 List<Intent> pendingIntents;
240
241 boolean startsNotResumed;
242 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800243 int pendingConfigChanges;
244 boolean onlyLocalRequest;
245
246 View mPendingRemoveWindow;
247 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700249 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 parent = null;
251 embeddedID = null;
252 paused = false;
253 stopped = false;
254 hideForNow = false;
255 nextIdle = null;
256 }
257
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800258 public boolean isPreHoneycomb() {
259 if (activity != null) {
260 return activity.getApplicationInfo().targetSdkVersion
261 < android.os.Build.VERSION_CODES.HONEYCOMB;
262 }
263 return false;
264 }
265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 public String toString() {
267 ComponentName componentName = intent.getComponent();
268 return "ActivityRecord{"
269 + Integer.toHexString(System.identityHashCode(this))
270 + " token=" + token + " " + (componentName == null
271 ? "no component name" : componentName.toShortString())
272 + "}";
273 }
274 }
275
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400276 final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 final String mName;
278 final IContentProvider mProvider;
279 final ContentProvider mLocalProvider;
280
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700281 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 ContentProvider localProvider) {
283 mName = name;
284 mProvider = provider;
285 mLocalProvider = localProvider;
286 }
287
288 public void binderDied() {
289 removeDeadProvider(mName, mProvider);
290 }
291 }
292
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400293 static final class NewIntentData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 List<Intent> intents;
295 IBinder token;
296 public String toString() {
297 return "NewIntentData{intents=" + intents + " token=" + token + "}";
298 }
299 }
300
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400301 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700302 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
303 boolean ordered, boolean sticky, IBinder token) {
304 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
305 this.intent = intent;
306 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 Intent intent;
309 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400310 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 public String toString() {
312 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700313 info.packageName + " resultCode=" + getResultCode()
314 + " resultData=" + getResultData() + " resultExtras="
315 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 }
317 }
318
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400319 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700320 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400321 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700322 int backupMode;
323 public String toString() {
324 return "CreateBackupAgentData{appInfo=" + appInfo
325 + " backupAgent=" + appInfo.backupAgentName
326 + " mode=" + backupMode + "}";
327 }
328 }
Bob Leee5408332009-09-04 18:31:17 -0700329
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400330 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 IBinder token;
332 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400333 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 Intent intent;
335 public String toString() {
336 return "CreateServiceData{token=" + token + " className="
337 + info.name + " packageName=" + info.packageName
338 + " intent=" + intent + "}";
339 }
340 }
341
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400342 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 IBinder token;
344 Intent intent;
345 boolean rebind;
346 public String toString() {
347 return "BindServiceData{token=" + token + " intent=" + intent + "}";
348 }
349 }
350
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400351 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700353 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700355 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 Intent args;
357 public String toString() {
358 return "ServiceArgsData{token=" + token + " startId=" + startId
359 + " args=" + args + "}";
360 }
361 }
362
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400363 static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700364 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 String processName;
366 ApplicationInfo appInfo;
367 List<ProviderInfo> providers;
368 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 Bundle instrumentationArgs;
370 IInstrumentationWatcher instrumentationWatcher;
371 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700372 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700373 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400375 CompatibilityInfo compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700376
377 /** Initial values for {@link Profiler}. */
378 String initProfileFile;
379 ParcelFileDescriptor initProfileFd;
380 boolean initAutoStopProfiler;
381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 public String toString() {
383 return "AppBindData{appInfo=" + appInfo + "}";
384 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700385 }
386
387 static final class Profiler {
388 String profileFile;
389 ParcelFileDescriptor profileFd;
390 boolean autoStopProfiler;
391 boolean profiling;
392 boolean handlingProfiling;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700393 public void setProfiler(String file, ParcelFileDescriptor fd) {
394 if (profiling) {
395 if (fd != null) {
396 try {
397 fd.close();
398 } catch (IOException e) {
399 }
400 }
401 return;
402 }
403 if (profileFd != null) {
404 try {
405 profileFd.close();
406 } catch (IOException e) {
407 }
408 }
409 profileFile = file;
410 profileFd = fd;
411 }
412 public void startProfiling() {
413 if (profileFd == null || profiling) {
414 return;
415 }
416 try {
417 Debug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
418 8 * 1024 * 1024, 0);
419 profiling = true;
420 } catch (RuntimeException e) {
421 Slog.w(TAG, "Profiling failed on path " + profileFile);
422 try {
423 profileFd.close();
424 profileFd = null;
425 } catch (IOException e2) {
426 Slog.w(TAG, "Failure closing profile fd", e2);
427 }
428 }
429 }
430 public void stopProfiling() {
431 if (profiling) {
432 profiling = false;
433 Debug.stopMethodTracing();
434 if (profileFd != null) {
435 try {
436 profileFd.close();
437 } catch (IOException e) {
438 }
439 }
440 profileFd = null;
441 profileFile = null;
442 }
443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 }
445
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400446 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700447 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700448 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800449 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400453 static final class ResultData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 IBinder token;
455 List<ResultInfo> results;
456 public String toString() {
457 return "ResultData{token=" + token + " results" + results + "}";
458 }
459 }
460
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400461 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800462 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 String what;
464 String who;
465 }
466
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400467 static final class ProfilerControlData {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700468 String path;
469 ParcelFileDescriptor fd;
470 }
471
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400472 static final class DumpHeapData {
Andy McFadden824c5102010-07-09 16:26:57 -0700473 String path;
474 ParcelFileDescriptor fd;
475 }
476
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400477 static final class UpdateCompatibilityData {
478 String pkg;
479 CompatibilityInfo info;
480 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -0700481
Romain Guy65b345f2011-07-27 18:51:50 -0700482 private native void dumpGraphicsInfo(FileDescriptor fd);
Chet Haase9c1e23b2011-03-24 10:51:31 -0700483
Romain Guy65b345f2011-07-27 18:51:50 -0700484 private class ApplicationThread extends ApplicationThreadNative {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700485 private static final String HEAP_COLUMN = "%13s %8s %8s %8s %8s %8s %8s";
486 private static final String ONE_COUNT_COLUMN = "%21s %8d";
487 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
488 private static final String TWO_COUNT_COLUMNS_DB = "%21s %8d %21s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700489 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 // Formatting for checkin service - update version if row format changes
492 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700493
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700494 private void updatePendingConfiguration(Configuration config) {
495 synchronized (mPackages) {
496 if (mPendingConfiguration == null ||
497 mPendingConfiguration.isOtherSeqNewer(config)) {
498 mPendingConfiguration = config;
499 }
500 }
501 }
502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 public final void schedulePauseActivity(IBinder token, boolean finished,
504 boolean userLeaving, int configChanges) {
505 queueOrSendMessage(
506 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
507 token,
508 (userLeaving ? 1 : 0),
509 configChanges);
510 }
511
512 public final void scheduleStopActivity(IBinder token, boolean showWindow,
513 int configChanges) {
514 queueOrSendMessage(
515 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
516 token, 0, configChanges);
517 }
518
519 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
520 queueOrSendMessage(
521 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
522 token);
523 }
524
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800525 public final void scheduleSleeping(IBinder token, boolean sleeping) {
526 queueOrSendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
527 }
528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
530 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
531 }
532
533 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
534 ResultData res = new ResultData();
535 res.token = token;
536 res.results = results;
537 queueOrSendMessage(H.SEND_RESULT, res);
538 }
539
540 // we use token to identify this activity without having to send the
541 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700542 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700543 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
544 Bundle state, List<ResultInfo> pendingResults,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700545 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
546 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700547 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548
549 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700550 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 r.intent = intent;
552 r.activityInfo = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400553 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 r.state = state;
555
556 r.pendingResults = pendingResults;
557 r.pendingIntents = pendingNewIntents;
558
559 r.startsNotResumed = notResumed;
560 r.isForward = isForward;
561
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700562 r.profileFile = profileName;
563 r.profileFd = profileFd;
564 r.autoStopProfiler = autoStopProfiler;
565
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700566 updatePendingConfiguration(curConfig);
567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
569 }
570
571 public final void scheduleRelaunchActivity(IBinder token,
572 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800573 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800574 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
575 configChanges, notResumed, config, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 }
577
578 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
579 NewIntentData data = new NewIntentData();
580 data.intents = intents;
581 data.token = token;
582
583 queueOrSendMessage(H.NEW_INTENT, data);
584 }
585
586 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
587 int configChanges) {
588 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
589 configChanges);
590 }
591
592 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400593 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
594 boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700595 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
596 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400598 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 queueOrSendMessage(H.RECEIVER, r);
600 }
601
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400602 public final void scheduleCreateBackupAgent(ApplicationInfo app,
603 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700604 CreateBackupAgentData d = new CreateBackupAgentData();
605 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400606 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700607 d.backupMode = backupMode;
608
609 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
610 }
611
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400612 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
613 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700614 CreateBackupAgentData d = new CreateBackupAgentData();
615 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400616 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700617
618 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
619 }
620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 public final void scheduleCreateService(IBinder token,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400622 ServiceInfo info, CompatibilityInfo compatInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 CreateServiceData s = new CreateServiceData();
624 s.token = token;
625 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400626 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627
628 queueOrSendMessage(H.CREATE_SERVICE, s);
629 }
630
631 public final void scheduleBindService(IBinder token, Intent intent,
632 boolean rebind) {
633 BindServiceData s = new BindServiceData();
634 s.token = token;
635 s.intent = intent;
636 s.rebind = rebind;
637
638 queueOrSendMessage(H.BIND_SERVICE, s);
639 }
640
641 public final void scheduleUnbindService(IBinder token, Intent intent) {
642 BindServiceData s = new BindServiceData();
643 s.token = token;
644 s.intent = intent;
645
646 queueOrSendMessage(H.UNBIND_SERVICE, s);
647 }
648
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700649 public final void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700650 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 ServiceArgsData s = new ServiceArgsData();
652 s.token = token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700653 s.taskRemoved = taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700655 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 s.args = args;
657
658 queueOrSendMessage(H.SERVICE_ARGS, s);
659 }
660
661 public final void scheduleStopService(IBinder token) {
662 queueOrSendMessage(H.STOP_SERVICE, token);
663 }
664
665 public final void bindApplication(String processName,
666 ApplicationInfo appInfo, List<ProviderInfo> providers,
667 ComponentName instrumentationName, String profileFile,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700668 ParcelFileDescriptor profileFd, boolean autoStopProfiler,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700670 int debugMode, boolean isRestrictedBackupMode, boolean persistent,
671 Configuration config, CompatibilityInfo compatInfo,
672 Map<String, IBinder> services, Bundle coreSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673
674 if (services != null) {
675 // Setup the service cache in the ServiceManager
676 ServiceManager.initServiceCache(services);
677 }
678
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800679 setCoreSettings(coreSettings);
680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 AppBindData data = new AppBindData();
682 data.processName = processName;
683 data.appInfo = appInfo;
684 data.providers = providers;
685 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 data.instrumentationArgs = instrumentationArgs;
687 data.instrumentationWatcher = instrumentationWatcher;
688 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700689 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700690 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400692 data.compatInfo = compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700693 data.initProfileFile = profileFile;
694 data.initProfileFd = profileFd;
695 data.initAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 queueOrSendMessage(H.BIND_APPLICATION, data);
697 }
698
699 public final void scheduleExit() {
700 queueOrSendMessage(H.EXIT_APPLICATION, null);
701 }
702
Christopher Tate5e1ab332009-09-01 20:32:49 -0700703 public final void scheduleSuicide() {
704 queueOrSendMessage(H.SUICIDE, null);
705 }
706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 public void requestThumbnail(IBinder token) {
708 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
709 }
710
711 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700712 updatePendingConfiguration(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
714 }
715
716 public void updateTimeZone() {
717 TimeZone.setDefault(null);
718 }
719
Robert Greenwalt03595d02010-11-02 14:08:23 -0700720 public void clearDnsCache() {
721 // a non-standard API to get this to libcore
722 InetAddress.clearDnsCache();
723 }
724
Robert Greenwalt434203a2010-10-11 16:00:27 -0700725 public void setHttpProxy(String host, String port, String exclList) {
726 Proxy.setHttpProxySystemProperty(host, port, exclList);
727 }
728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 public void processInBackground() {
730 mH.removeMessages(H.GC_WHEN_IDLE);
731 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
732 }
733
734 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700735 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700736 try {
737 data.fd = ParcelFileDescriptor.dup(fd);
738 data.token = servicetoken;
739 data.args = args;
740 queueOrSendMessage(H.DUMP_SERVICE, data);
741 } catch (IOException e) {
742 Slog.w(TAG, "dumpService failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 }
744 }
745
746 // This function exists to make sure all receiver dispatching is
747 // correctly ordered, since these are one-way calls and the binder driver
748 // applies transaction ordering per object for such calls.
749 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700750 int resultCode, String dataStr, Bundle extras, boolean ordered,
751 boolean sticky) throws RemoteException {
752 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
Bob Leee5408332009-09-04 18:31:17 -0700754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 public void scheduleLowMemory() {
756 queueOrSendMessage(H.LOW_MEMORY, null);
757 }
758
759 public void scheduleActivityConfigurationChanged(IBinder token) {
760 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
761 }
762
Romain Guy7eabe552011-07-21 14:56:34 -0700763 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd,
764 int profileType) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700765 ProfilerControlData pcd = new ProfilerControlData();
766 pcd.path = path;
767 pcd.fd = fd;
Romain Guy7eabe552011-07-21 14:56:34 -0700768 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800769 }
770
Andy McFadden824c5102010-07-09 16:26:57 -0700771 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
772 DumpHeapData dhd = new DumpHeapData();
773 dhd.path = path;
774 dhd.fd = fd;
775 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
776 }
777
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700778 public void setSchedulingGroup(int group) {
779 // Note: do this immediately, since going into the foreground
780 // should happen regardless of what pending work we have to do
781 // and the activity manager will wait for us to report back that
782 // we are done before sending us to the background.
783 try {
784 Process.setProcessGroup(Process.myPid(), group);
785 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800786 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700787 }
788 }
Bob Leee5408332009-09-04 18:31:17 -0700789
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700790 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
791 Debug.getMemoryInfo(outInfo);
792 }
Bob Leee5408332009-09-04 18:31:17 -0700793
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700794 public void dispatchPackageBroadcast(int cmd, String[] packages) {
795 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
796 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700797
798 public void scheduleCrash(String msg) {
799 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
800 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700801
Dianne Hackborn30d71892010-12-11 10:37:55 -0800802 public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
803 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700804 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700805 try {
806 data.fd = ParcelFileDescriptor.dup(fd);
807 data.token = activitytoken;
808 data.prefix = prefix;
809 data.args = args;
810 queueOrSendMessage(H.DUMP_ACTIVITY, data);
811 } catch (IOException e) {
812 Slog.w(TAG, "dumpActivity failed", e);
Dianne Hackborn625ac272010-09-17 18:29:22 -0700813 }
814 }
Chet Haase9c1e23b2011-03-24 10:51:31 -0700815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 @Override
Dianne Hackbornb437e092011-08-05 17:50:29 -0700817 public Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, boolean checkin,
818 boolean all, String[] args) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700819 FileOutputStream fout = new FileOutputStream(fd);
820 PrintWriter pw = new PrintWriter(fout);
821 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -0700822 return dumpMemInfo(pw, checkin, all, args);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700823 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -0700824 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -0700825 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700826 }
827
Dianne Hackbornb437e092011-08-05 17:50:29 -0700828 private Debug.MemoryInfo dumpMemInfo(PrintWriter pw, boolean checkin, boolean all,
829 String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 long nativeMax = Debug.getNativeHeapSize() / 1024;
831 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
832 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
833
834 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
835 Debug.getMemoryInfo(memInfo);
836
Dianne Hackbornb437e092011-08-05 17:50:29 -0700837 if (!all) {
838 return memInfo;
839 }
840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 Runtime runtime = Runtime.getRuntime();
842
843 long dalvikMax = runtime.totalMemory() / 1024;
844 long dalvikFree = runtime.freeMemory() / 1024;
845 long dalvikAllocated = dalvikMax - dalvikFree;
846 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -0700847 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700848 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
849 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 int globalAssetCount = AssetManager.getGlobalAssetCount();
851 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
852 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
853 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
854 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700855 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800857 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 // For checkin, we print one long comma-separated list of values
Dianne Hackbornb437e092011-08-05 17:50:29 -0700860 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 // NOTE: if you change anything significant below, also consider changing
862 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700863 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 // Header
867 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
868 pw.print(Process.myPid()); pw.print(',');
869 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 // Heap info - max
872 pw.print(nativeMax); pw.print(',');
873 pw.print(dalvikMax); pw.print(',');
874 pw.print("N/A,");
875 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 // Heap info - allocated
878 pw.print(nativeAllocated); pw.print(',');
879 pw.print(dalvikAllocated); pw.print(',');
880 pw.print("N/A,");
881 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 // Heap info - free
884 pw.print(nativeFree); pw.print(',');
885 pw.print(dalvikFree); pw.print(',');
886 pw.print("N/A,");
887 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 // Heap info - proportional set size
890 pw.print(memInfo.nativePss); pw.print(',');
891 pw.print(memInfo.dalvikPss); pw.print(',');
892 pw.print(memInfo.otherPss); pw.print(',');
893 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 // Heap info - shared
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700896 pw.print(memInfo.nativeSharedDirty); pw.print(',');
897 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
898 pw.print(memInfo.otherSharedDirty); pw.print(',');
899 pw.print(memInfo.nativeSharedDirty + memInfo.dalvikSharedDirty
900 + memInfo.otherSharedDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 // Heap info - private
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700903 pw.print(memInfo.nativePrivateDirty); pw.print(',');
904 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
905 pw.print(memInfo.otherPrivateDirty); pw.print(',');
906 pw.print(memInfo.nativePrivateDirty + memInfo.dalvikPrivateDirty
907 + memInfo.otherPrivateDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 // Object counts
910 pw.print(viewInstanceCount); pw.print(',');
911 pw.print(viewRootInstanceCount); pw.print(',');
912 pw.print(appContextInstanceCount); pw.print(',');
913 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 pw.print(globalAssetCount); pw.print(',');
916 pw.print(globalAssetManagerCount); pw.print(',');
917 pw.print(binderLocalObjectCount); pw.print(',');
918 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 pw.print(binderDeathObjectCount); pw.print(',');
921 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 // SQL
924 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800925 pw.print(stats.memoryUsed / 1024); pw.print(',');
926 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -0700927 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800928 for (int i = 0; i < stats.dbStats.size(); i++) {
929 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -0700930 pw.print(','); pw.print(dbStats.dbName);
931 pw.print(','); pw.print(dbStats.pageSize);
932 pw.print(','); pw.print(dbStats.dbSize);
933 pw.print(','); pw.print(dbStats.lookaside);
934 pw.print(','); pw.print(dbStats.cache);
935 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -0800936 }
Dianne Hackbornb437e092011-08-05 17:50:29 -0700937 pw.println();
Bob Leee5408332009-09-04 18:31:17 -0700938
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700939 return memInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 }
Bob Leee5408332009-09-04 18:31:17 -0700941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 // otherwise, show human-readable format
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700943 printRow(pw, HEAP_COLUMN, "", "", "Shared", "Private", "Heap", "Heap", "Heap");
944 printRow(pw, HEAP_COLUMN, "", "Pss", "Dirty", "Dirty", "Size", "Alloc", "Free");
945 printRow(pw, HEAP_COLUMN, "", "------", "------", "------", "------", "------",
946 "------");
947 printRow(pw, HEAP_COLUMN, "Native", memInfo.nativePss, memInfo.nativeSharedDirty,
948 memInfo.nativePrivateDirty, nativeMax, nativeAllocated, nativeFree);
949 printRow(pw, HEAP_COLUMN, "Dalvik", memInfo.dalvikPss, memInfo.dalvikSharedDirty,
950 memInfo.dalvikPrivateDirty, dalvikMax, dalvikAllocated, dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700952 int otherPss = memInfo.otherPss;
953 int otherSharedDirty = memInfo.otherSharedDirty;
954 int otherPrivateDirty = memInfo.otherPrivateDirty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700956 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Romain Guy65b345f2011-07-27 18:51:50 -0700957 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700958 memInfo.getOtherPss(i), memInfo.getOtherSharedDirty(i),
959 memInfo.getOtherPrivateDirty(i), "", "", "");
960 otherPss -= memInfo.getOtherPss(i);
961 otherSharedDirty -= memInfo.getOtherSharedDirty(i);
962 otherPrivateDirty -= memInfo.getOtherPrivateDirty(i);
963 }
964
965 printRow(pw, HEAP_COLUMN, "Unknown", otherPss, otherSharedDirty,
966 otherPrivateDirty, "", "", "");
967 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
968 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
969 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
970 nativeFree+dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971
972 pw.println(" ");
973 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -0700974 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 viewRootInstanceCount);
976
977 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
978 "Activities:", activityInstanceCount);
979
980 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
981 "AssetManagers:", globalAssetManagerCount);
982
983 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
984 "Proxy Binders:", binderProxyObjectCount);
985 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
986
987 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 // SQLite mem info
990 pw.println(" ");
991 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700992 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800993 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700994 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
995 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800996 pw.println(" ");
997 int N = stats.dbStats.size();
998 if (N > 0) {
999 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -07001000 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
1001 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001002 for (int i = 0; i < N; i++) {
1003 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001004 printRow(pw, DB_INFO_FORMAT,
1005 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1006 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1007 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1008 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001009 }
1010 }
Bob Leee5408332009-09-04 18:31:17 -07001011
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001012 // Asset details.
1013 String assetAlloc = AssetManager.getAssetAllocations();
1014 if (assetAlloc != null) {
1015 pw.println(" ");
1016 pw.println(" Asset Allocations");
1017 pw.print(assetAlloc);
1018 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001019
1020 return memInfo;
1021 }
1022
1023 @Override
1024 public void dumpGfxInfo(FileDescriptor fd, String[] args) {
1025 dumpGraphicsInfo(fd);
Romain Guy65b345f2011-07-27 18:51:50 -07001026 WindowManagerImpl.getDefault().dumpGfxInfo(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
1028
1029 private void printRow(PrintWriter pw, String format, Object...objs) {
1030 pw.println(String.format(format, objs));
1031 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001032
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001033 public void setCoreSettings(Bundle coreSettings) {
1034 queueOrSendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001035 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001036
1037 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1038 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1039 ucd.pkg = pkg;
1040 ucd.info = info;
1041 queueOrSendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
1042 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001043
1044 public void scheduleTrimMemory(int level) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001045 queueOrSendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048
Romain Guy65b345f2011-07-27 18:51:50 -07001049 private class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 public static final int LAUNCH_ACTIVITY = 100;
1051 public static final int PAUSE_ACTIVITY = 101;
1052 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1053 public static final int STOP_ACTIVITY_SHOW = 103;
1054 public static final int STOP_ACTIVITY_HIDE = 104;
1055 public static final int SHOW_WINDOW = 105;
1056 public static final int HIDE_WINDOW = 106;
1057 public static final int RESUME_ACTIVITY = 107;
1058 public static final int SEND_RESULT = 108;
Brian Carlstromed7e0072011-03-24 13:27:57 -07001059 public static final int DESTROY_ACTIVITY = 109;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 public static final int BIND_APPLICATION = 110;
1061 public static final int EXIT_APPLICATION = 111;
1062 public static final int NEW_INTENT = 112;
1063 public static final int RECEIVER = 113;
1064 public static final int CREATE_SERVICE = 114;
1065 public static final int SERVICE_ARGS = 115;
1066 public static final int STOP_SERVICE = 116;
1067 public static final int REQUEST_THUMBNAIL = 117;
1068 public static final int CONFIGURATION_CHANGED = 118;
1069 public static final int CLEAN_UP_CONTEXT = 119;
1070 public static final int GC_WHEN_IDLE = 120;
1071 public static final int BIND_SERVICE = 121;
1072 public static final int UNBIND_SERVICE = 122;
1073 public static final int DUMP_SERVICE = 123;
1074 public static final int LOW_MEMORY = 124;
1075 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1076 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001077 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001078 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001079 public static final int DESTROY_BACKUP_AGENT = 129;
1080 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001081 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001082 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001083 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001084 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001085 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001086 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001087 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001088 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001089 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001090 public static final int TRIM_MEMORY = 140;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001092 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 switch (code) {
1094 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1095 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1096 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1097 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1098 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1099 case SHOW_WINDOW: return "SHOW_WINDOW";
1100 case HIDE_WINDOW: return "HIDE_WINDOW";
1101 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1102 case SEND_RESULT: return "SEND_RESULT";
1103 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1104 case BIND_APPLICATION: return "BIND_APPLICATION";
1105 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1106 case NEW_INTENT: return "NEW_INTENT";
1107 case RECEIVER: return "RECEIVER";
1108 case CREATE_SERVICE: return "CREATE_SERVICE";
1109 case SERVICE_ARGS: return "SERVICE_ARGS";
1110 case STOP_SERVICE: return "STOP_SERVICE";
1111 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1112 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1113 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1114 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1115 case BIND_SERVICE: return "BIND_SERVICE";
1116 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1117 case DUMP_SERVICE: return "DUMP_SERVICE";
1118 case LOW_MEMORY: return "LOW_MEMORY";
1119 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1120 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001121 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001122 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1123 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001124 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001125 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001126 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001127 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001128 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001129 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001130 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001131 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001132 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001133 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001134 case TRIM_MEMORY: return "TRIM_MEMORY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 }
1136 }
1137 return "(unknown)";
1138 }
1139 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001140 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 switch (msg.what) {
1142 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001143 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144
1145 r.packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001146 r.activityInfo.applicationInfo, r.compatInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001147 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 } break;
1149 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001150 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001151 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 } break;
1153 case PAUSE_ACTIVITY:
1154 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001155 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 break;
1157 case PAUSE_ACTIVITY_FINISHING:
1158 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1159 break;
1160 case STOP_ACTIVITY_SHOW:
1161 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1162 break;
1163 case STOP_ACTIVITY_HIDE:
1164 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1165 break;
1166 case SHOW_WINDOW:
1167 handleWindowVisibility((IBinder)msg.obj, true);
1168 break;
1169 case HIDE_WINDOW:
1170 handleWindowVisibility((IBinder)msg.obj, false);
1171 break;
1172 case RESUME_ACTIVITY:
1173 handleResumeActivity((IBinder)msg.obj, true,
1174 msg.arg1 != 0);
1175 break;
1176 case SEND_RESULT:
1177 handleSendResult((ResultData)msg.obj);
1178 break;
1179 case DESTROY_ACTIVITY:
1180 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1181 msg.arg2, false);
1182 break;
1183 case BIND_APPLICATION:
1184 AppBindData data = (AppBindData)msg.obj;
1185 handleBindApplication(data);
1186 break;
1187 case EXIT_APPLICATION:
1188 if (mInitialApplication != null) {
1189 mInitialApplication.onTerminate();
1190 }
1191 Looper.myLooper().quit();
1192 break;
1193 case NEW_INTENT:
1194 handleNewIntent((NewIntentData)msg.obj);
1195 break;
1196 case RECEIVER:
1197 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001198 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 break;
1200 case CREATE_SERVICE:
1201 handleCreateService((CreateServiceData)msg.obj);
1202 break;
1203 case BIND_SERVICE:
1204 handleBindService((BindServiceData)msg.obj);
1205 break;
1206 case UNBIND_SERVICE:
1207 handleUnbindService((BindServiceData)msg.obj);
1208 break;
1209 case SERVICE_ARGS:
1210 handleServiceArgs((ServiceArgsData)msg.obj);
1211 break;
1212 case STOP_SERVICE:
1213 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001214 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 break;
1216 case REQUEST_THUMBNAIL:
1217 handleRequestThumbnail((IBinder)msg.obj);
1218 break;
1219 case CONFIGURATION_CHANGED:
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001220 handleConfigurationChanged((Configuration)msg.obj, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 break;
1222 case CLEAN_UP_CONTEXT:
1223 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1224 cci.context.performFinalCleanup(cci.who, cci.what);
1225 break;
1226 case GC_WHEN_IDLE:
1227 scheduleGcIdler();
1228 break;
1229 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001230 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 break;
1232 case LOW_MEMORY:
1233 handleLowMemory();
1234 break;
1235 case ACTIVITY_CONFIGURATION_CHANGED:
1236 handleActivityConfigurationChanged((IBinder)msg.obj);
1237 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001238 case PROFILER_CONTROL:
Romain Guy7eabe552011-07-21 14:56:34 -07001239 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001240 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001241 case CREATE_BACKUP_AGENT:
1242 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1243 break;
1244 case DESTROY_BACKUP_AGENT:
1245 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1246 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001247 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001248 Process.killProcess(Process.myPid());
1249 break;
1250 case REMOVE_PROVIDER:
1251 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001252 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001253 case ENABLE_JIT:
1254 ensureJitEnabled();
1255 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001256 case DISPATCH_PACKAGE_BROADCAST:
1257 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1258 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001259 case SCHEDULE_CRASH:
1260 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001261 case DUMP_HEAP:
1262 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1263 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001264 case DUMP_ACTIVITY:
1265 handleDumpActivity((DumpComponentInfo)msg.obj);
1266 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001267 case SLEEPING:
1268 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
1269 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001270 case SET_CORE_SETTINGS:
1271 handleSetCoreSettings((Bundle) msg.obj);
1272 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001273 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1274 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001275 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001276 case TRIM_MEMORY:
1277 handleTrimMemory(msg.arg1);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001278 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001280 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
Bob Leee5408332009-09-04 18:31:17 -07001282
Brian Carlstromed7e0072011-03-24 13:27:57 -07001283 private void maybeSnapshot() {
1284 if (mBoundApplication != null && SamplingProfilerIntegration.isEnabled()) {
Sen Hubde75702010-05-28 01:54:03 -07001285 // convert the *private* ActivityThread.PackageInfo to *public* known
1286 // android.content.pm.PackageInfo
1287 String packageName = mBoundApplication.info.mPackageName;
1288 android.content.pm.PackageInfo packageInfo = null;
1289 try {
1290 Context context = getSystemContext();
1291 if(context == null) {
1292 Log.e(TAG, "cannot get a valid context");
1293 return;
1294 }
1295 PackageManager pm = context.getPackageManager();
1296 if(pm == null) {
1297 Log.e(TAG, "cannot get a valid PackageManager");
1298 return;
1299 }
1300 packageInfo = pm.getPackageInfo(
1301 packageName, PackageManager.GET_ACTIVITIES);
1302 } catch (NameNotFoundException e) {
1303 Log.e(TAG, "cannot get package info for " + packageName, e);
1304 }
1305 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001306 }
1307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
1309
Romain Guy65b345f2011-07-27 18:51:50 -07001310 private class Idler implements MessageQueue.IdleHandler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001312 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001313 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001314 if (mBoundApplication != null && mProfiler.profileFd != null
1315 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001316 stopProfiling = true;
1317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 if (a != null) {
1319 mNewActivities = null;
1320 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001321 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001323 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 TAG, "Reporting idle of " + a +
1325 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001326 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 if (a.activity != null && !a.activity.mFinished) {
1328 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001329 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001330 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07001332 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
1334 }
1335 prev = a;
1336 a = a.nextIdle;
1337 prev.nextIdle = null;
1338 } while (a != null);
1339 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001340 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001341 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001342 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001343 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 return false;
1345 }
1346 }
1347
1348 final class GcIdler implements MessageQueue.IdleHandler {
1349 public final boolean queueIdle() {
1350 doGcIfNeeded();
1351 return false;
1352 }
1353 }
1354
Romain Guy65b345f2011-07-27 18:51:50 -07001355 private static class ResourcesKey {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001356 final private String mResDir;
1357 final private float mScale;
1358 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001359
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001360 ResourcesKey(String resDir, float scale) {
1361 mResDir = resDir;
1362 mScale = scale;
1363 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1364 }
Bob Leee5408332009-09-04 18:31:17 -07001365
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001366 @Override
1367 public int hashCode() {
1368 return mHash;
1369 }
1370
1371 @Override
1372 public boolean equals(Object obj) {
1373 if (!(obj instanceof ResourcesKey)) {
1374 return false;
1375 }
1376 ResourcesKey peer = (ResourcesKey) obj;
1377 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1378 }
1379 }
1380
Romain Guy65b345f2011-07-27 18:51:50 -07001381 public static ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001382 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384
Romain Guy65b345f2011-07-27 18:51:50 -07001385 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001386 ActivityThread am = currentActivityThread();
1387 return (am != null && am.mBoundApplication != null)
1388 ? am.mBoundApplication.processName : null;
1389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390
Romain Guy65b345f2011-07-27 18:51:50 -07001391 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001392 ActivityThread am = currentActivityThread();
1393 return am != null ? am.mInitialApplication : null;
1394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001396 public static IPackageManager getPackageManager() {
1397 if (sPackageManager != null) {
1398 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1399 return sPackageManager;
1400 }
1401 IBinder b = ServiceManager.getService("package");
1402 //Slog.v("PackageManager", "default service binder = " + b);
1403 sPackageManager = IPackageManager.Stub.asInterface(b);
1404 //Slog.v("PackageManager", "default service = " + sPackageManager);
1405 return sPackageManager;
1406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001408 DisplayMetrics getDisplayMetricsLocked(CompatibilityInfo ci, boolean forceUpdate) {
1409 DisplayMetrics dm = mDisplayMetrics.get(ci);
1410 if (dm != null && !forceUpdate) {
1411 return dm;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001412 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001413 if (dm == null) {
1414 dm = new DisplayMetrics();
1415 mDisplayMetrics.put(ci, dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001416 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001417 Display d = WindowManagerImpl.getDefault(ci).getDefaultDisplay();
1418 d.getMetrics(dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001419 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1420 // + metrics.heightPixels + " den=" + metrics.density
1421 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001422 return dm;
1423 }
1424
1425 static Configuration applyConfigCompat(Configuration config, CompatibilityInfo compat) {
1426 if (config == null) {
1427 return null;
1428 }
1429 if (compat != null && !compat.supportsScreen()) {
1430 config = new Configuration(config);
1431 compat.applyToConfiguration(config);
1432 }
1433 return config;
1434 }
1435
Romain Guy65b345f2011-07-27 18:51:50 -07001436 private Configuration mMainThreadConfig = new Configuration();
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001437 Configuration applyConfigCompatMainThread(Configuration config, CompatibilityInfo compat) {
1438 if (config == null) {
1439 return null;
1440 }
1441 if (compat != null && !compat.supportsScreen()) {
1442 mMainThreadConfig.setTo(config);
1443 config = mMainThreadConfig;
1444 compat.applyToConfiguration(config);
1445 }
1446 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001449 /**
1450 * Creates the top level Resources for applications with the given compatibility info.
1451 *
1452 * @param resDir the resource directory.
1453 * @param compInfo the compability info. It will use the default compatibility info when it's
1454 * null.
1455 */
1456 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1457 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1458 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001460 // Resources is app scale dependent.
1461 if (false) {
1462 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1463 + compInfo.applicationScale);
1464 }
1465 WeakReference<Resources> wr = mActiveResources.get(key);
1466 r = wr != null ? wr.get() : null;
1467 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1468 if (r != null && r.getAssets().isUpToDate()) {
1469 if (false) {
1470 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1471 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1472 }
1473 return r;
1474 }
1475 }
1476
1477 //if (r != null) {
1478 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1479 // + r + " " + resDir);
1480 //}
1481
1482 AssetManager assets = new AssetManager();
1483 if (assets.addAssetPath(resDir) == 0) {
1484 return null;
1485 }
1486
1487 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Dianne Hackborn836e2622011-10-04 18:32:39 -07001488 DisplayMetrics metrics = getDisplayMetricsLocked(null, false);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001489 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1490 if (false) {
1491 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1492 + r.getConfiguration() + " appScale="
1493 + r.getCompatibilityInfo().applicationScale);
1494 }
1495
1496 synchronized (mPackages) {
1497 WeakReference<Resources> wr = mActiveResources.get(key);
1498 Resources existing = wr != null ? wr.get() : null;
1499 if (existing != null && existing.getAssets().isUpToDate()) {
1500 // Someone else already created the resources while we were
1501 // unlocked; go ahead and use theirs.
1502 r.getAssets().close();
1503 return existing;
1504 }
1505
1506 // XXX need to remove entries when weak references go away
1507 mActiveResources.put(key, new WeakReference<Resources>(r));
1508 return r;
1509 }
1510 }
1511
1512 /**
1513 * Creates the top level resources for the given package.
1514 */
1515 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001516 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo.get());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001517 }
1518
1519 final Handler getHandler() {
1520 return mH;
1521 }
1522
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001523 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1524 int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001525 synchronized (mPackages) {
1526 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1528 ref = mPackages.get(packageName);
1529 } else {
1530 ref = mResourcePackages.get(packageName);
1531 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001532 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001533 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001534 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1535 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 if (packageInfo != null && (packageInfo.mResources == null
1537 || packageInfo.mResources.getAssets().isUpToDate())) {
1538 if (packageInfo.isSecurityViolation()
1539 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1540 throw new SecurityException(
1541 "Requesting code from " + packageName
1542 + " to be run in process "
1543 + mBoundApplication.processName
1544 + "/" + mBoundApplication.appInfo.uid);
1545 }
1546 return packageInfo;
1547 }
1548 }
1549
1550 ApplicationInfo ai = null;
1551 try {
1552 ai = getPackageManager().getApplicationInfo(packageName,
1553 PackageManager.GET_SHARED_LIBRARY_FILES);
1554 } catch (RemoteException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07001555 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 }
1557
1558 if (ai != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001559 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561
1562 return null;
1563 }
1564
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001565 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
1566 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1568 boolean securityViolation = includeCode && ai.uid != 0
1569 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1570 ? ai.uid != mBoundApplication.appInfo.uid : true);
1571 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1572 |Context.CONTEXT_IGNORE_SECURITY))
1573 == Context.CONTEXT_INCLUDE_CODE) {
1574 if (securityViolation) {
1575 String msg = "Requesting code from " + ai.packageName
1576 + " (with uid " + ai.uid + ")";
1577 if (mBoundApplication != null) {
1578 msg = msg + " to be run in process "
1579 + mBoundApplication.processName + " (with uid "
1580 + mBoundApplication.appInfo.uid + ")";
1581 }
1582 throw new SecurityException(msg);
1583 }
1584 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001585 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001588 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
1589 CompatibilityInfo compatInfo) {
1590 return getPackageInfo(ai, compatInfo, null, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 }
1592
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001593 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
1594 synchronized (mPackages) {
1595 WeakReference<LoadedApk> ref;
1596 if (includeCode) {
1597 ref = mPackages.get(packageName);
1598 } else {
1599 ref = mResourcePackages.get(packageName);
1600 }
1601 return ref != null ? ref.get() : null;
1602 }
1603 }
1604
Romain Guy65b345f2011-07-27 18:51:50 -07001605 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1607 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001608 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 if (includeCode) {
1610 ref = mPackages.get(aInfo.packageName);
1611 } else {
1612 ref = mResourcePackages.get(aInfo.packageName);
1613 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001614 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 if (packageInfo == null || (packageInfo.mResources != null
1616 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001617 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 : "Loading resource-only package ") + aInfo.packageName
1619 + " (in " + (mBoundApplication != null
1620 ? mBoundApplication.processName : null)
1621 + ")");
1622 packageInfo =
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001623 new LoadedApk(this, aInfo, compatInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 securityViolation, includeCode &&
1625 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1626 if (includeCode) {
1627 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001628 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 } else {
1630 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001631 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
1633 }
1634 return packageInfo;
1635 }
1636 }
1637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 ActivityThread() {
1639 }
1640
1641 public ApplicationThread getApplicationThread()
1642 {
1643 return mAppThread;
1644 }
1645
1646 public Instrumentation getInstrumentation()
1647 {
1648 return mInstrumentation;
1649 }
1650
1651 public Configuration getConfiguration() {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001652 return mResConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 }
1654
1655 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001656 return mProfiler != null && mProfiler.profileFile != null
1657 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
1659
1660 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001661 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663
1664 public Looper getLooper() {
1665 return mLooper;
1666 }
1667
1668 public Application getApplication() {
1669 return mInitialApplication;
1670 }
Bob Leee5408332009-09-04 18:31:17 -07001671
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001672 public String getProcessName() {
1673 return mBoundApplication.processName;
1674 }
Bob Leee5408332009-09-04 18:31:17 -07001675
Dianne Hackborn21556372010-02-04 16:34:40 -08001676 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 synchronized (this) {
1678 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001679 ContextImpl context =
1680 ContextImpl.createSystemContext(this);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001681 LoadedApk info = new LoadedApk(this, "android", context, null,
1682 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 context.init(info, null, this);
1684 context.getResources().updateConfiguration(
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001685 getConfiguration(), getDisplayMetricsLocked(
1686 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001688 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 // + ": " + context.getResources().getConfiguration());
1690 }
1691 }
1692 return mSystemContext;
1693 }
1694
Mike Cleron432b7132009-09-24 15:28:29 -07001695 public void installSystemApplicationInfo(ApplicationInfo info) {
1696 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001697 ContextImpl context = getSystemContext();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001698 context.init(new LoadedApk(this, "android", context, info,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001699 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO), null, this);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001700
1701 // give ourselves a default profiler
1702 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07001703 }
1704 }
1705
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001706 void ensureJitEnabled() {
1707 if (!mJitEnabled) {
1708 mJitEnabled = true;
1709 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1710 }
1711 }
1712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 void scheduleGcIdler() {
1714 if (!mGcIdlerScheduled) {
1715 mGcIdlerScheduled = true;
1716 Looper.myQueue().addIdleHandler(mGcIdler);
1717 }
1718 mH.removeMessages(H.GC_WHEN_IDLE);
1719 }
1720
1721 void unscheduleGcIdler() {
1722 if (mGcIdlerScheduled) {
1723 mGcIdlerScheduled = false;
1724 Looper.myQueue().removeIdleHandler(mGcIdler);
1725 }
1726 mH.removeMessages(H.GC_WHEN_IDLE);
1727 }
1728
1729 void doGcIfNeeded() {
1730 mGcIdlerScheduled = false;
1731 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001732 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 // + "m now=" + now);
1734 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001735 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 BinderInternal.forceGc("bg");
1737 }
1738 }
1739
Jeff Hamilton52d32032011-01-08 15:31:26 -06001740 public void registerOnActivityPausedListener(Activity activity,
1741 OnActivityPausedListener listener) {
1742 synchronized (mOnPauseListeners) {
1743 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1744 if (list == null) {
1745 list = new ArrayList<OnActivityPausedListener>();
1746 mOnPauseListeners.put(activity, list);
1747 }
1748 list.add(listener);
1749 }
1750 }
1751
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08001752 public void unregisterOnActivityPausedListener(Activity activity,
1753 OnActivityPausedListener listener) {
1754 synchronized (mOnPauseListeners) {
1755 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1756 if (list != null) {
1757 list.remove(listener);
1758 }
1759 }
1760 }
1761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 public final ActivityInfo resolveActivityInfo(Intent intent) {
1763 ActivityInfo aInfo = intent.resolveActivityInfo(
1764 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1765 if (aInfo == null) {
1766 // Throw an exception.
1767 Instrumentation.checkStartActivityResult(
1768 IActivityManager.START_CLASS_NOT_FOUND, intent);
1769 }
1770 return aInfo;
1771 }
Bob Leee5408332009-09-04 18:31:17 -07001772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001775 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001776 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001778 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 r.intent = intent;
1780 r.state = state;
1781 r.parent = parent;
1782 r.embeddedID = id;
1783 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001784 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 if (localLOGV) {
1786 ComponentName compname = intent.getComponent();
1787 String name;
1788 if (compname != null) {
1789 name = compname.toShortString();
1790 } else {
1791 name = "(Intent " + intent + ").getComponent() returned null";
1792 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001793 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 + ", comp=" + name
1795 + ", token=" + token);
1796 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001797 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
1799
1800 public final Activity getActivity(IBinder token) {
1801 return mActivities.get(token).activity;
1802 }
1803
1804 public final void sendActivityResult(
1805 IBinder token, String id, int requestCode,
1806 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001807 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001808 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1810 list.add(new ResultInfo(id, requestCode, resultCode, data));
1811 mAppThread.scheduleSendResult(token, list);
1812 }
1813
1814 // if the thread hasn't started yet, we don't have the handler, so just
1815 // save the messages until we're ready.
Romain Guy65b345f2011-07-27 18:51:50 -07001816 private void queueOrSendMessage(int what, Object obj) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 queueOrSendMessage(what, obj, 0, 0);
1818 }
1819
Romain Guy65b345f2011-07-27 18:51:50 -07001820 private void queueOrSendMessage(int what, Object obj, int arg1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 queueOrSendMessage(what, obj, arg1, 0);
1822 }
1823
Romain Guy65b345f2011-07-27 18:51:50 -07001824 private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001826 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1828 + ": " + arg1 + " / " + obj);
1829 Message msg = Message.obtain();
1830 msg.what = what;
1831 msg.obj = obj;
1832 msg.arg1 = arg1;
1833 msg.arg2 = arg2;
1834 mH.sendMessage(msg);
1835 }
1836 }
1837
Dianne Hackborn21556372010-02-04 16:34:40 -08001838 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 String what) {
1840 ContextCleanupInfo cci = new ContextCleanupInfo();
1841 cci.context = context;
1842 cci.who = who;
1843 cci.what = what;
1844 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1845 }
1846
Romain Guy65b345f2011-07-27 18:51:50 -07001847 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1849
1850 ActivityInfo aInfo = r.activityInfo;
1851 if (r.packageInfo == null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001852 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 Context.CONTEXT_INCLUDE_CODE);
1854 }
Bob Leee5408332009-09-04 18:31:17 -07001855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 ComponentName component = r.intent.getComponent();
1857 if (component == null) {
1858 component = r.intent.resolveActivity(
1859 mInitialApplication.getPackageManager());
1860 r.intent.setComponent(component);
1861 }
1862
1863 if (r.activityInfo.targetActivity != null) {
1864 component = new ComponentName(r.activityInfo.packageName,
1865 r.activityInfo.targetActivity);
1866 }
1867
1868 Activity activity = null;
1869 try {
1870 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1871 activity = mInstrumentation.newActivity(
1872 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001873 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 r.intent.setExtrasClassLoader(cl);
1875 if (r.state != null) {
1876 r.state.setClassLoader(cl);
1877 }
1878 } catch (Exception e) {
1879 if (!mInstrumentation.onException(activity, e)) {
1880 throw new RuntimeException(
1881 "Unable to instantiate activity " + component
1882 + ": " + e.toString(), e);
1883 }
1884 }
1885
1886 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001887 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001888
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001889 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1890 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 TAG, r + ": app=" + app
1892 + ", appName=" + app.getPackageName()
1893 + ", pkg=" + r.packageInfo.getPackageName()
1894 + ", comp=" + r.intent.getComponent().toShortString()
1895 + ", dir=" + r.packageInfo.getAppDir());
1896
1897 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001898 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 appContext.init(r.packageInfo, r.token, this);
1900 appContext.setOuterContext(activity);
1901 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001902 Configuration config = new Configuration(mCompatConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001903 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001904 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001905 activity.attach(appContext, this, getInstrumentation(), r.token,
1906 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001907 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001908
Christopher Tateb70f3df2009-04-07 16:07:59 -07001909 if (customIntent != null) {
1910 activity.mIntent = customIntent;
1911 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001912 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 activity.mStartedActivity = false;
1914 int theme = r.activityInfo.getThemeResource();
1915 if (theme != 0) {
1916 activity.setTheme(theme);
1917 }
1918
1919 activity.mCalled = false;
1920 mInstrumentation.callActivityOnCreate(activity, r.state);
1921 if (!activity.mCalled) {
1922 throw new SuperNotCalledException(
1923 "Activity " + r.intent.getComponent().toShortString() +
1924 " did not call through to super.onCreate()");
1925 }
1926 r.activity = activity;
1927 r.stopped = true;
1928 if (!r.activity.mFinished) {
1929 activity.performStart();
1930 r.stopped = false;
1931 }
1932 if (!r.activity.mFinished) {
1933 if (r.state != null) {
1934 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1935 }
1936 }
1937 if (!r.activity.mFinished) {
1938 activity.mCalled = false;
1939 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1940 if (!activity.mCalled) {
1941 throw new SuperNotCalledException(
1942 "Activity " + r.intent.getComponent().toShortString() +
1943 " did not call through to super.onPostCreate()");
1944 }
1945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
1947 r.paused = true;
1948
1949 mActivities.put(r.token, r);
1950
1951 } catch (SuperNotCalledException e) {
1952 throw e;
1953
1954 } catch (Exception e) {
1955 if (!mInstrumentation.onException(activity, e)) {
1956 throw new RuntimeException(
1957 "Unable to start activity " + component
1958 + ": " + e.toString(), e);
1959 }
1960 }
1961
1962 return activity;
1963 }
1964
Romain Guy65b345f2011-07-27 18:51:50 -07001965 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 // If we are getting ready to gc after going to the background, well
1967 // we are back active so skip it.
1968 unscheduleGcIdler();
1969
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001970 if (r.profileFd != null) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001971 mProfiler.setProfiler(r.profileFile, r.profileFd);
1972 mProfiler.startProfiling();
1973 mProfiler.autoStopProfiler = r.autoStopProfiler;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001974 }
1975
Dianne Hackborn58f42a52011-10-10 13:46:34 -07001976 // Make sure we are running with the most recent config.
1977 handleConfigurationChanged(null, null);
1978
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001979 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001981 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982
1983 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001984 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001985 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 handleResumeActivity(r.token, false, r.isForward);
1987
1988 if (!r.activity.mFinished && r.startsNotResumed) {
1989 // The activity manager actually wants this one to start out
1990 // paused, because it needs to be visible but isn't in the
1991 // foreground. We accomplish this by going through the
1992 // normal startup (because activities expect to go through
1993 // onResume() the first time they run, before their window
1994 // is displayed), and then pausing it. However, in this case
1995 // we do -not- need to do the full pause cycle (of freezing
1996 // and such) because the activity manager assumes it can just
1997 // retain the current state it has.
1998 try {
1999 r.activity.mCalled = false;
2000 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002001 // We need to keep around the original state, in case
2002 // we need to be created again.
2003 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 if (!r.activity.mCalled) {
2005 throw new SuperNotCalledException(
2006 "Activity " + r.intent.getComponent().toShortString() +
2007 " did not call through to super.onPause()");
2008 }
2009
2010 } catch (SuperNotCalledException e) {
2011 throw e;
2012
2013 } catch (Exception e) {
2014 if (!mInstrumentation.onException(r.activity, e)) {
2015 throw new RuntimeException(
2016 "Unable to pause activity "
2017 + r.intent.getComponent().toShortString()
2018 + ": " + e.toString(), e);
2019 }
2020 }
2021 r.paused = true;
2022 }
2023 } else {
2024 // If there was an error, for any reason, tell the activity
2025 // manager to stop us.
2026 try {
2027 ActivityManagerNative.getDefault()
2028 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2029 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07002030 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
2032 }
2033 }
2034
Romain Guy65b345f2011-07-27 18:51:50 -07002035 private void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 List<Intent> intents) {
2037 final int N = intents.size();
2038 for (int i=0; i<N; i++) {
2039 Intent intent = intents.get(i);
2040 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002041 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2043 }
2044 }
2045
2046 public final void performNewIntents(IBinder token,
2047 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002048 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 if (r != null) {
2050 final boolean resumed = !r.paused;
2051 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002052 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 mInstrumentation.callActivityOnPause(r.activity);
2054 }
2055 deliverNewIntents(r, intents);
2056 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07002057 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002058 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
2060 }
2061 }
Bob Leee5408332009-09-04 18:31:17 -07002062
Romain Guy65b345f2011-07-27 18:51:50 -07002063 private void handleNewIntent(NewIntentData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 performNewIntents(data.token, data.intents);
2065 }
2066
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002067 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
2068
2069 /**
2070 * Return the Intent that's currently being handled by a
2071 * BroadcastReceiver on this thread, or null if none.
2072 * @hide
2073 */
2074 public static Intent getIntentBeingBroadcast() {
2075 return sCurrentBroadcastIntent.get();
2076 }
2077
Romain Guy65b345f2011-07-27 18:51:50 -07002078 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 // If we are getting ready to gc after going to the background, well
2080 // we are back active so skip it.
2081 unscheduleGcIdler();
2082
2083 String component = data.intent.getComponent().getClassName();
2084
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002085 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002086 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087
2088 IActivityManager mgr = ActivityManagerNative.getDefault();
2089
Romain Guy65b345f2011-07-27 18:51:50 -07002090 BroadcastReceiver receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 try {
2092 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2093 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002094 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2096 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002097 if (DEBUG_BROADCAST) Slog.i(TAG,
2098 "Finishing failed broadcast to " + data.intent.getComponent());
2099 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 throw new RuntimeException(
2101 "Unable to instantiate receiver " + component
2102 + ": " + e.toString(), e);
2103 }
2104
2105 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002106 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002107
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002108 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 TAG, "Performing receive of " + data.intent
2110 + ": app=" + app
2111 + ", appName=" + app.getPackageName()
2112 + ", pkg=" + packageInfo.getPackageName()
2113 + ", comp=" + data.intent.getComponent().toShortString()
2114 + ", dir=" + packageInfo.getAppDir());
2115
Dianne Hackborn21556372010-02-04 16:34:40 -08002116 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002117 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002118 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 receiver.onReceive(context.getReceiverRestrictedContext(),
2120 data.intent);
2121 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002122 if (DEBUG_BROADCAST) Slog.i(TAG,
2123 "Finishing failed broadcast to " + data.intent.getComponent());
2124 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 if (!mInstrumentation.onException(receiver, e)) {
2126 throw new RuntimeException(
2127 "Unable to start receiver " + component
2128 + ": " + e.toString(), e);
2129 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002130 } finally {
2131 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 }
2133
Dianne Hackborne829fef2010-10-26 17:44:01 -07002134 if (receiver.getPendingResult() != null) {
2135 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136 }
2137 }
2138
Christopher Tate181fafa2009-05-14 11:12:14 -07002139 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07002140 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002141 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002142
2143 // no longer idle; we have backup work to do
2144 unscheduleGcIdler();
2145
2146 // instantiate the BackupAgent class named in the manifest
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002147 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002148 String packageName = packageInfo.mPackageName;
2149 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002150 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07002151 + " already exists");
2152 return;
2153 }
Bob Leee5408332009-09-04 18:31:17 -07002154
Christopher Tate181fafa2009-05-14 11:12:14 -07002155 BackupAgent agent = null;
2156 String classname = data.appInfo.backupAgentName;
Christopher Tate4a627c72011-04-01 14:43:32 -07002157
Christopher Tate79ec80d2011-06-24 14:58:49 -07002158 // full backup operation but no app-supplied agent? use the default implementation
2159 if (classname == null && (data.backupMode == IApplicationThread.BACKUP_MODE_FULL
2160 || data.backupMode == IApplicationThread.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002161 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07002162 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002163
Christopher Tate181fafa2009-05-14 11:12:14 -07002164 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002165 IBinder binder = null;
2166 try {
Christopher Tate4a627c72011-04-01 14:43:32 -07002167 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
2168
Christopher Tated1475e02009-07-09 15:36:17 -07002169 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Christopher Tate4a627c72011-04-01 14:43:32 -07002170 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tated1475e02009-07-09 15:36:17 -07002171
2172 // set up the agent's context
Dianne Hackborn21556372010-02-04 16:34:40 -08002173 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07002174 context.init(packageInfo, null, this);
2175 context.setOuterContext(agent);
2176 agent.attach(context);
2177
2178 agent.onCreate();
2179 binder = agent.onBind();
2180 mBackupAgents.put(packageName, agent);
2181 } catch (Exception e) {
2182 // If this is during restore, fail silently; otherwise go
2183 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002184 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tate75a99702011-05-18 16:28:19 -07002185 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE
2186 && data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE_FULL) {
Christopher Tated1475e02009-07-09 15:36:17 -07002187 throw e;
2188 }
2189 // falling through with 'binder' still null
2190 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002191
2192 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002193 try {
2194 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2195 } catch (RemoteException e) {
2196 // nothing to do.
2197 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002198 } catch (Exception e) {
2199 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07002200 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07002201 }
2202 }
2203
2204 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07002205 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002206 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002207
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002208 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002209 String packageName = packageInfo.mPackageName;
2210 BackupAgent agent = mBackupAgents.get(packageName);
2211 if (agent != null) {
2212 try {
2213 agent.onDestroy();
2214 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002215 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002216 e.printStackTrace();
2217 }
2218 mBackupAgents.remove(packageName);
2219 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002220 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002221 }
2222 }
2223
Romain Guy65b345f2011-07-27 18:51:50 -07002224 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 // If we are getting ready to gc after going to the background, well
2226 // we are back active so skip it.
2227 unscheduleGcIdler();
2228
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002229 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002230 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 Service service = null;
2232 try {
2233 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2234 service = (Service) cl.loadClass(data.info.name).newInstance();
2235 } catch (Exception e) {
2236 if (!mInstrumentation.onException(service, e)) {
2237 throw new RuntimeException(
2238 "Unable to instantiate service " + data.info.name
2239 + ": " + e.toString(), e);
2240 }
2241 }
2242
2243 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002244 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245
Dianne Hackborn21556372010-02-04 16:34:40 -08002246 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 context.init(packageInfo, null, this);
2248
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002249 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 context.setOuterContext(service);
2251 service.attach(context, this, data.info.name, data.token, app,
2252 ActivityManagerNative.getDefault());
2253 service.onCreate();
2254 mServices.put(data.token, service);
2255 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002256 ActivityManagerNative.getDefault().serviceDoneExecuting(
2257 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 } catch (RemoteException e) {
2259 // nothing to do.
2260 }
2261 } catch (Exception e) {
2262 if (!mInstrumentation.onException(service, e)) {
2263 throw new RuntimeException(
2264 "Unable to create service " + data.info.name
2265 + ": " + e.toString(), e);
2266 }
2267 }
2268 }
2269
Romain Guy65b345f2011-07-27 18:51:50 -07002270 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 Service s = mServices.get(data.token);
2272 if (s != null) {
2273 try {
2274 data.intent.setExtrasClassLoader(s.getClassLoader());
2275 try {
2276 if (!data.rebind) {
2277 IBinder binder = s.onBind(data.intent);
2278 ActivityManagerNative.getDefault().publishService(
2279 data.token, data.intent, binder);
2280 } else {
2281 s.onRebind(data.intent);
2282 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002283 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002285 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 } catch (RemoteException ex) {
2287 }
2288 } catch (Exception e) {
2289 if (!mInstrumentation.onException(s, e)) {
2290 throw new RuntimeException(
2291 "Unable to bind to service " + s
2292 + " with " + data.intent + ": " + e.toString(), e);
2293 }
2294 }
2295 }
2296 }
2297
Romain Guy65b345f2011-07-27 18:51:50 -07002298 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 Service s = mServices.get(data.token);
2300 if (s != null) {
2301 try {
2302 data.intent.setExtrasClassLoader(s.getClassLoader());
2303 boolean doRebind = s.onUnbind(data.intent);
2304 try {
2305 if (doRebind) {
2306 ActivityManagerNative.getDefault().unbindFinished(
2307 data.token, data.intent, doRebind);
2308 } else {
2309 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002310 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 }
2312 } catch (RemoteException ex) {
2313 }
2314 } catch (Exception e) {
2315 if (!mInstrumentation.onException(s, e)) {
2316 throw new RuntimeException(
2317 "Unable to unbind to service " + s
2318 + " with " + data.intent + ": " + e.toString(), e);
2319 }
2320 }
2321 }
2322 }
2323
Dianne Hackborn625ac272010-09-17 18:29:22 -07002324 private void handleDumpService(DumpComponentInfo info) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002325 Service s = mServices.get(info.token);
2326 if (s != null) {
2327 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2328 s.dump(info.fd.getFileDescriptor(), pw, info.args);
2329 pw.flush();
2330 try {
2331 info.fd.close();
2332 } catch (IOException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 }
2334 }
2335 }
2336
Dianne Hackborn625ac272010-09-17 18:29:22 -07002337 private void handleDumpActivity(DumpComponentInfo info) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002338 ActivityClientRecord r = mActivities.get(info.token);
2339 if (r != null && r.activity != null) {
2340 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2341 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
2342 pw.flush();
2343 try {
2344 info.fd.close();
2345 } catch (IOException e) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002346 }
2347 }
2348 }
2349
Romain Guy65b345f2011-07-27 18:51:50 -07002350 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 Service s = mServices.get(data.token);
2352 if (s != null) {
2353 try {
2354 if (data.args != null) {
2355 data.args.setExtrasClassLoader(s.getClassLoader());
2356 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002357 int res;
2358 if (!data.taskRemoved) {
2359 res = s.onStartCommand(data.args, data.flags, data.startId);
2360 } else {
2361 s.onTaskRemoved(data.args);
2362 res = Service.START_TASK_REMOVED_COMPLETE;
2363 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002364
2365 QueuedWork.waitToFinish();
2366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002368 ActivityManagerNative.getDefault().serviceDoneExecuting(
2369 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 } catch (RemoteException e) {
2371 // nothing to do.
2372 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002373 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 } catch (Exception e) {
2375 if (!mInstrumentation.onException(s, e)) {
2376 throw new RuntimeException(
2377 "Unable to start service " + s
2378 + " with " + data.args + ": " + e.toString(), e);
2379 }
2380 }
2381 }
2382 }
2383
Romain Guy65b345f2011-07-27 18:51:50 -07002384 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 Service s = mServices.remove(token);
2386 if (s != null) {
2387 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002388 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 s.onDestroy();
2390 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002391 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002393 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002395
2396 QueuedWork.waitToFinish();
2397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002399 ActivityManagerNative.getDefault().serviceDoneExecuting(
2400 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 } catch (RemoteException e) {
2402 // nothing to do.
2403 }
2404 } catch (Exception e) {
2405 if (!mInstrumentation.onException(s, e)) {
2406 throw new RuntimeException(
2407 "Unable to stop service " + s
2408 + ": " + e.toString(), e);
2409 }
2410 }
2411 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002412 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 }
2414
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002415 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002417 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002418 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 + " finished=" + r.activity.mFinished);
2420 if (r != null && !r.activity.mFinished) {
2421 if (clearHide) {
2422 r.hideForNow = false;
2423 r.activity.mStartedActivity = false;
2424 }
2425 try {
2426 if (r.pendingIntents != null) {
2427 deliverNewIntents(r, r.pendingIntents);
2428 r.pendingIntents = null;
2429 }
2430 if (r.pendingResults != null) {
2431 deliverResults(r, r.pendingResults);
2432 r.pendingResults = null;
2433 }
2434 r.activity.performResume();
2435
Bob Leee5408332009-09-04 18:31:17 -07002436 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 r.paused = false;
2440 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 r.state = null;
2442 } catch (Exception e) {
2443 if (!mInstrumentation.onException(r.activity, e)) {
2444 throw new RuntimeException(
2445 "Unable to resume activity "
2446 + r.intent.getComponent().toShortString()
2447 + ": " + e.toString(), e);
2448 }
2449 }
2450 }
2451 return r;
2452 }
2453
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002454 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
2455 if (r.mPendingRemoveWindow != null) {
2456 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2457 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2458 if (wtoken != null) {
2459 WindowManagerImpl.getDefault().closeAll(wtoken,
2460 r.activity.getClass().getName(), "Activity");
2461 }
2462 }
2463 r.mPendingRemoveWindow = null;
2464 r.mPendingRemoveWindowManager = null;
2465 }
2466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2468 // If we are getting ready to gc after going to the background, well
2469 // we are back active so skip it.
2470 unscheduleGcIdler();
2471
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002472 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473
2474 if (r != null) {
2475 final Activity a = r.activity;
2476
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002477 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 TAG, "Resume " + r + " started activity: " +
2479 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2480 + ", finished: " + a.mFinished);
2481
2482 final int forwardBit = isForward ?
2483 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 // If the window hasn't yet been added to the window manager,
2486 // and this guy didn't finish itself or start another activity,
2487 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002488 boolean willBeVisible = !a.mStartedActivity;
2489 if (!willBeVisible) {
2490 try {
2491 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2492 a.getActivityToken());
2493 } catch (RemoteException e) {
2494 }
2495 }
2496 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 r.window = r.activity.getWindow();
2498 View decor = r.window.getDecorView();
2499 decor.setVisibility(View.INVISIBLE);
2500 ViewManager wm = a.getWindowManager();
2501 WindowManager.LayoutParams l = r.window.getAttributes();
2502 a.mDecor = decor;
2503 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2504 l.softInputMode |= forwardBit;
2505 if (a.mVisibleFromClient) {
2506 a.mWindowAdded = true;
2507 wm.addView(decor, l);
2508 }
2509
2510 // If the window has already been added, but during resume
2511 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002512 // window visible.
2513 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002514 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 TAG, "Launch " + r + " mStartedActivity set");
2516 r.hideForNow = true;
2517 }
2518
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002519 // Get rid of anything left hanging around.
2520 cleanUpPendingRemoveWindows(r);
2521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 // The window is now visible if it has been added, we are not
2523 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002524 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002525 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002527 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002528 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 performConfigurationChanged(r.activity, r.newConfig);
2530 r.newConfig = null;
2531 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002532 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 + isForward);
2534 WindowManager.LayoutParams l = r.window.getAttributes();
2535 if ((l.softInputMode
2536 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2537 != forwardBit) {
2538 l.softInputMode = (l.softInputMode
2539 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2540 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002541 if (r.activity.mVisibleFromClient) {
2542 ViewManager wm = a.getWindowManager();
2543 View decor = r.window.getDecorView();
2544 wm.updateViewLayout(decor, l);
2545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 }
2547 r.activity.mVisibleFromServer = true;
2548 mNumVisibleActivities++;
2549 if (r.activity.mVisibleFromClient) {
2550 r.activity.makeVisible();
2551 }
2552 }
2553
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002554 if (!r.onlyLocalRequest) {
2555 r.nextIdle = mNewActivities;
2556 mNewActivities = r;
2557 if (localLOGV) Slog.v(
2558 TAG, "Scheduling idle handler for " + r);
2559 Looper.myQueue().addIdleHandler(new Idler());
2560 }
2561 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562
2563 } else {
2564 // If an exception was thrown when trying to resume, then
2565 // just end this activity.
2566 try {
2567 ActivityManagerNative.getDefault()
2568 .finishActivity(token, Activity.RESULT_CANCELED, null);
2569 } catch (RemoteException ex) {
2570 }
2571 }
2572 }
2573
2574 private int mThumbnailWidth = -1;
2575 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002576 private Bitmap mAvailThumbnailBitmap = null;
2577 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578
Romain Guy65b345f2011-07-27 18:51:50 -07002579 private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002580 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002582 if (thumbnail == null) {
2583 int w = mThumbnailWidth;
2584 int h;
2585 if (w < 0) {
2586 Resources res = r.activity.getResources();
2587 mThumbnailHeight = h =
2588 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002590 mThumbnailWidth = w =
2591 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2592 } else {
2593 h = mThumbnailHeight;
2594 }
2595
2596 // On platforms where we don't want thumbnails, set dims to (0,0)
2597 if ((w > 0) && (h > 0)) {
2598 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2599 thumbnail.eraseColor(0);
2600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 }
2602
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002603 if (thumbnail != null) {
2604 Canvas cv = mThumbnailCanvas;
2605 if (cv == null) {
2606 mThumbnailCanvas = cv = new Canvas();
2607 }
2608
2609 cv.setBitmap(thumbnail);
2610 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2611 mAvailThumbnailBitmap = thumbnail;
2612 thumbnail = null;
2613 }
Dianne Hackborn6311d0a2011-08-02 16:37:58 -07002614 cv.setBitmap(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 } catch (Exception e) {
2618 if (!mInstrumentation.onException(r.activity, e)) {
2619 throw new RuntimeException(
2620 "Unable to create thumbnail of "
2621 + r.intent.getComponent().toShortString()
2622 + ": " + e.toString(), e);
2623 }
2624 thumbnail = null;
2625 }
2626
2627 return thumbnail;
2628 }
2629
Romain Guy65b345f2011-07-27 18:51:50 -07002630 private void handlePauseActivity(IBinder token, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002632 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002634 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 if (userLeaving) {
2636 performUserLeavingActivity(r);
2637 }
Bob Leee5408332009-09-04 18:31:17 -07002638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002640 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002642 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002643 if (r.isPreHoneycomb()) {
2644 QueuedWork.waitToFinish();
2645 }
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 // Tell the activity manager we have paused.
2648 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002649 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 } catch (RemoteException ex) {
2651 }
2652 }
2653 }
2654
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002655 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 mInstrumentation.callActivityOnUserLeaving(r.activity);
2657 }
2658
2659 final Bundle performPauseActivity(IBinder token, boolean finished,
2660 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002661 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 return r != null ? performPauseActivity(r, finished, saveState) : null;
2663 }
2664
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002665 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 boolean saveState) {
2667 if (r.paused) {
2668 if (r.activity.mFinished) {
2669 // If we are finishing, we won't call onResume() in certain cases.
2670 // So here we likewise don't want to call onPause() if the activity
2671 // isn't resumed.
2672 return null;
2673 }
2674 RuntimeException e = new RuntimeException(
2675 "Performing pause of activity that is not resumed: "
2676 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002677 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 }
2679 Bundle state = null;
2680 if (finished) {
2681 r.activity.mFinished = true;
2682 }
2683 try {
2684 // Next have the activity save its current state and managed dialogs...
2685 if (!r.activity.mFinished && saveState) {
2686 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002687 state.setAllowFds(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2689 r.state = state;
2690 }
2691 // Now we are idle.
2692 r.activity.mCalled = false;
2693 mInstrumentation.callActivityOnPause(r.activity);
2694 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2695 if (!r.activity.mCalled) {
2696 throw new SuperNotCalledException(
2697 "Activity " + r.intent.getComponent().toShortString() +
2698 " did not call through to super.onPause()");
2699 }
2700
2701 } catch (SuperNotCalledException e) {
2702 throw e;
2703
2704 } catch (Exception e) {
2705 if (!mInstrumentation.onException(r.activity, e)) {
2706 throw new RuntimeException(
2707 "Unable to pause activity "
2708 + r.intent.getComponent().toShortString()
2709 + ": " + e.toString(), e);
2710 }
2711 }
2712 r.paused = true;
Jeff Hamilton52d32032011-01-08 15:31:26 -06002713
2714 // Notify any outstanding on paused listeners
2715 ArrayList<OnActivityPausedListener> listeners;
2716 synchronized (mOnPauseListeners) {
2717 listeners = mOnPauseListeners.remove(r.activity);
2718 }
2719 int size = (listeners != null ? listeners.size() : 0);
2720 for (int i = 0; i < size; i++) {
2721 listeners.get(i).onPaused(r.activity);
2722 }
2723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 return state;
2725 }
2726
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002727 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002728 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002729 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 }
2731
2732 private static class StopInfo {
2733 Bitmap thumbnail;
2734 CharSequence description;
2735 }
2736
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002737 private static final class ProviderRefCount {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 public int count;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 ProviderRefCount(int pCount) {
2741 count = pCount;
2742 }
2743 }
2744
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002745 /**
2746 * Core implementation of stopping an activity. Note this is a little
2747 * tricky because the server's meaning of stop is slightly different
2748 * than our client -- for the server, stop means to save state and give
2749 * it the result when it is done, but the window may still be visible.
2750 * For the client, we want to call onStop()/onStart() to indicate when
2751 * the activity's UI visibillity changes.
2752 */
Romain Guy65b345f2011-07-27 18:51:50 -07002753 private void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002754 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002755 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002756 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 if (r != null) {
2758 if (!keepShown && r.stopped) {
2759 if (r.activity.mFinished) {
2760 // If we are finishing, we won't call onResume() in certain
2761 // cases. So here we likewise don't want to call onStop()
2762 // if the activity isn't resumed.
2763 return;
2764 }
2765 RuntimeException e = new RuntimeException(
2766 "Performing stop of activity that is not resumed: "
2767 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002768 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 }
2770
2771 if (info != null) {
2772 try {
2773 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07002774 // For now, don't create the thumbnail here; we are
2775 // doing that by doing a screen snapshot.
2776 info.thumbnail = null; //createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 info.description = r.activity.onCreateDescription();
2778 } catch (Exception e) {
2779 if (!mInstrumentation.onException(r.activity, e)) {
2780 throw new RuntimeException(
2781 "Unable to save state of activity "
2782 + r.intent.getComponent().toShortString()
2783 + ": " + e.toString(), e);
2784 }
2785 }
2786 }
2787
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002788 // Next have the activity save its current state and managed dialogs...
2789 if (!r.activity.mFinished && saveState) {
2790 if (r.state == null) {
2791 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002792 state.setAllowFds(false);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002793 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2794 r.state = state;
2795 } else {
2796 state = r.state;
2797 }
2798 }
2799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 if (!keepShown) {
2801 try {
2802 // Now we are idle.
2803 r.activity.performStop();
2804 } catch (Exception e) {
2805 if (!mInstrumentation.onException(r.activity, e)) {
2806 throw new RuntimeException(
2807 "Unable to stop activity "
2808 + r.intent.getComponent().toShortString()
2809 + ": " + e.toString(), e);
2810 }
2811 }
2812 r.stopped = true;
2813 }
2814
2815 r.paused = true;
2816 }
2817 }
2818
Romain Guy65b345f2011-07-27 18:51:50 -07002819 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 View v = r.activity.mDecor;
2821 if (v != null) {
2822 if (show) {
2823 if (!r.activity.mVisibleFromServer) {
2824 r.activity.mVisibleFromServer = true;
2825 mNumVisibleActivities++;
2826 if (r.activity.mVisibleFromClient) {
2827 r.activity.makeVisible();
2828 }
2829 }
2830 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002831 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002832 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 performConfigurationChanged(r.activity, r.newConfig);
2834 r.newConfig = null;
2835 }
2836 } else {
2837 if (r.activity.mVisibleFromServer) {
2838 r.activity.mVisibleFromServer = false;
2839 mNumVisibleActivities--;
2840 v.setVisibility(View.INVISIBLE);
2841 }
2842 }
2843 }
2844 }
2845
Romain Guy65b345f2011-07-27 18:51:50 -07002846 private void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002847 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 r.activity.mConfigChangeFlags |= configChanges;
2849
2850 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002851 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002853 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 TAG, "Finishing stop of " + r + ": show=" + show
2855 + " win=" + r.window);
2856
2857 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002858
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002859 // Make sure any pending writes are now committed.
2860 if (!r.isPreHoneycomb()) {
2861 QueuedWork.waitToFinish();
2862 }
2863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 // Tell activity manager we have been stopped.
2865 try {
2866 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002867 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 } catch (RemoteException ex) {
2869 }
2870 }
2871
2872 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002873 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 if (r.stopped) {
2875 r.activity.performRestart();
2876 r.stopped = false;
2877 }
2878 }
2879
Romain Guy65b345f2011-07-27 18:51:50 -07002880 private void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002881 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002882
2883 if (r == null) {
2884 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2885 return;
2886 }
2887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002889 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 } else if (show && r.stopped) {
2891 // If we are getting ready to gc after going to the background, well
2892 // we are back active so skip it.
2893 unscheduleGcIdler();
2894
2895 r.activity.performRestart();
2896 r.stopped = false;
2897 }
2898 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07002899 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 TAG, "Handle window " + r + " visibility: " + show);
2901 updateVisibility(r, show);
2902 }
2903 }
2904
Romain Guy65b345f2011-07-27 18:51:50 -07002905 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002906 ActivityClientRecord r = mActivities.get(token);
2907
2908 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002909 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002910 return;
2911 }
2912
2913 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002914 if (!r.stopped && !r.isPreHoneycomb()) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002915 try {
2916 // Now we are idle.
2917 r.activity.performStop();
2918 } catch (Exception e) {
2919 if (!mInstrumentation.onException(r.activity, e)) {
2920 throw new RuntimeException(
2921 "Unable to stop activity "
2922 + r.intent.getComponent().toShortString()
2923 + ": " + e.toString(), e);
2924 }
2925 }
2926 r.stopped = true;
2927 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002928
2929 // Make sure any pending writes are now committed.
2930 if (!r.isPreHoneycomb()) {
2931 QueuedWork.waitToFinish();
2932 }
2933
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002934 // Tell activity manager we slept.
2935 try {
2936 ActivityManagerNative.getDefault().activitySlept(r.token);
2937 } catch (RemoteException ex) {
2938 }
2939 } else {
2940 if (r.stopped && r.activity.mVisibleFromServer) {
2941 r.activity.performRestart();
2942 r.stopped = false;
2943 }
2944 }
2945 }
2946
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002947 private void handleSetCoreSettings(Bundle coreSettings) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08002948 synchronized (mPackages) {
2949 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002950 }
2951 }
2952
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002953 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
2954 LoadedApk apk = peekPackageInfo(data.pkg, false);
2955 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002956 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002957 }
2958 apk = peekPackageInfo(data.pkg, true);
2959 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002960 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002961 }
2962 handleConfigurationChanged(mConfiguration, data.info);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002963 WindowManagerImpl.getDefault().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002964 }
2965
Romain Guy65b345f2011-07-27 18:51:50 -07002966 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 final int N = results.size();
2968 for (int i=0; i<N; i++) {
2969 ResultInfo ri = results.get(i);
2970 try {
2971 if (ri.mData != null) {
2972 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2973 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002974 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002975 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 r.activity.dispatchActivityResult(ri.mResultWho,
2977 ri.mRequestCode, ri.mResultCode, ri.mData);
2978 } catch (Exception e) {
2979 if (!mInstrumentation.onException(r.activity, e)) {
2980 throw new RuntimeException(
2981 "Failure delivering result " + ri + " to activity "
2982 + r.intent.getComponent().toShortString()
2983 + ": " + e.toString(), e);
2984 }
2985 }
2986 }
2987 }
2988
Romain Guy65b345f2011-07-27 18:51:50 -07002989 private void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002990 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002991 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 if (r != null) {
2993 final boolean resumed = !r.paused;
2994 if (!r.activity.mFinished && r.activity.mDecor != null
2995 && r.hideForNow && resumed) {
2996 // We had hidden the activity because it started another
2997 // one... we have gotten a result back and we are not
2998 // paused, so make sure our window is visible.
2999 updateVisibility(r, true);
3000 }
3001 if (resumed) {
3002 try {
3003 // Now we are idle.
3004 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003005 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 mInstrumentation.callActivityOnPause(r.activity);
3007 if (!r.activity.mCalled) {
3008 throw new SuperNotCalledException(
3009 "Activity " + r.intent.getComponent().toShortString()
3010 + " did not call through to super.onPause()");
3011 }
3012 } catch (SuperNotCalledException e) {
3013 throw e;
3014 } catch (Exception e) {
3015 if (!mInstrumentation.onException(r.activity, e)) {
3016 throw new RuntimeException(
3017 "Unable to pause activity "
3018 + r.intent.getComponent().toShortString()
3019 + ": " + e.toString(), e);
3020 }
3021 }
3022 }
3023 deliverResults(r, res.results);
3024 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07003025 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003026 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 }
3028 }
3029 }
3030
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003031 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 return performDestroyActivity(token, finishing, 0, false);
3033 }
3034
Romain Guy65b345f2011-07-27 18:51:50 -07003035 private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003037 ActivityClientRecord r = mActivities.get(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003038 Class activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003039 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003041 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 r.activity.mConfigChangeFlags |= configChanges;
3043 if (finishing) {
3044 r.activity.mFinished = true;
3045 }
3046 if (!r.paused) {
3047 try {
3048 r.activity.mCalled = false;
3049 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003050 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 r.activity.getComponentName().getClassName());
3052 if (!r.activity.mCalled) {
3053 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003054 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 + " did not call through to super.onPause()");
3056 }
3057 } catch (SuperNotCalledException e) {
3058 throw e;
3059 } catch (Exception e) {
3060 if (!mInstrumentation.onException(r.activity, e)) {
3061 throw new RuntimeException(
3062 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003063 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 + ": " + e.toString(), e);
3065 }
3066 }
3067 r.paused = true;
3068 }
3069 if (!r.stopped) {
3070 try {
3071 r.activity.performStop();
3072 } catch (SuperNotCalledException e) {
3073 throw e;
3074 } catch (Exception e) {
3075 if (!mInstrumentation.onException(r.activity, e)) {
3076 throw new RuntimeException(
3077 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003078 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 + ": " + e.toString(), e);
3080 }
3081 }
3082 r.stopped = true;
3083 }
3084 if (getNonConfigInstance) {
3085 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003086 r.lastNonConfigurationInstances
3087 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 } catch (Exception e) {
3089 if (!mInstrumentation.onException(r.activity, e)) {
3090 throw new RuntimeException(
3091 "Unable to retain activity "
3092 + r.intent.getComponent().toShortString()
3093 + ": " + e.toString(), e);
3094 }
3095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 }
3097 try {
3098 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07003099 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 if (!r.activity.mCalled) {
3101 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003102 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 " did not call through to super.onDestroy()");
3104 }
3105 if (r.window != null) {
3106 r.window.closeAllPanels();
3107 }
3108 } catch (SuperNotCalledException e) {
3109 throw e;
3110 } catch (Exception e) {
3111 if (!mInstrumentation.onException(r.activity, e)) {
3112 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003113 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3114 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 }
3116 }
3117 }
3118 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003119 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 return r;
3121 }
3122
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003123 private static String safeToComponentShortString(Intent intent) {
3124 ComponentName component = intent.getComponent();
3125 return component == null ? "[Unknown]" : component.toShortString();
3126 }
3127
Romain Guy65b345f2011-07-27 18:51:50 -07003128 private void handleDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003130 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 configChanges, getNonConfigInstance);
3132 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003133 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 WindowManager wm = r.activity.getWindowManager();
3135 View v = r.activity.mDecor;
3136 if (v != null) {
3137 if (r.activity.mVisibleFromServer) {
3138 mNumVisibleActivities--;
3139 }
3140 IBinder wtoken = v.getWindowToken();
3141 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003142 if (r.onlyLocalRequest) {
3143 // Hold off on removing this until the new activity's
3144 // window is being added.
3145 r.mPendingRemoveWindow = v;
3146 r.mPendingRemoveWindowManager = wm;
3147 } else {
3148 wm.removeViewImmediate(v);
3149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003151 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 WindowManagerImpl.getDefault().closeAll(wtoken,
3153 r.activity.getClass().getName(), "Activity");
3154 }
3155 r.activity.mDecor = null;
3156 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003157 if (r.mPendingRemoveWindow == null) {
3158 // If we are delaying the removal of the activity window, then
3159 // we can't clean up all windows here. Note that we can't do
3160 // so later either, which means any windows that aren't closed
3161 // by the app will leak. Well we try to warning them a lot
3162 // about leaking windows, because that is a bug, so if they are
3163 // using this recreate facility then they get to live with leaks.
3164 WindowManagerImpl.getDefault().closeAll(token,
3165 r.activity.getClass().getName(), "Activity");
3166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167
3168 // Mocked out contexts won't be participating in the normal
3169 // process lifecycle, but if we're running with a proper
3170 // ApplicationContext we need to have it tear down things
3171 // cleanly.
3172 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003173 if (c instanceof ContextImpl) {
3174 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 r.activity.getClass().getName(), "Activity");
3176 }
3177 }
3178 if (finishing) {
3179 try {
3180 ActivityManagerNative.getDefault().activityDestroyed(token);
3181 } catch (RemoteException ex) {
3182 // If the system process has died, it's game over for everyone.
3183 }
3184 }
3185 }
3186
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003187 public final void requestRelaunchActivity(IBinder token,
3188 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
3189 int configChanges, boolean notResumed, Configuration config,
3190 boolean fromServer) {
3191 ActivityClientRecord target = null;
3192
3193 synchronized (mPackages) {
3194 for (int i=0; i<mRelaunchingActivities.size(); i++) {
3195 ActivityClientRecord r = mRelaunchingActivities.get(i);
3196 if (r.token == token) {
3197 target = r;
3198 if (pendingResults != null) {
3199 if (r.pendingResults != null) {
3200 r.pendingResults.addAll(pendingResults);
3201 } else {
3202 r.pendingResults = pendingResults;
3203 }
3204 }
3205 if (pendingNewIntents != null) {
3206 if (r.pendingIntents != null) {
3207 r.pendingIntents.addAll(pendingNewIntents);
3208 } else {
3209 r.pendingIntents = pendingNewIntents;
3210 }
3211 }
3212 break;
3213 }
3214 }
3215
3216 if (target == null) {
3217 target = new ActivityClientRecord();
3218 target.token = token;
3219 target.pendingResults = pendingResults;
3220 target.pendingIntents = pendingNewIntents;
3221 if (!fromServer) {
3222 ActivityClientRecord existing = mActivities.get(token);
3223 if (existing != null) {
3224 target.startsNotResumed = existing.paused;
3225 }
3226 target.onlyLocalRequest = true;
3227 }
3228 mRelaunchingActivities.add(target);
3229 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
3230 }
3231
3232 if (fromServer) {
3233 target.startsNotResumed = notResumed;
3234 target.onlyLocalRequest = false;
3235 }
3236 if (config != null) {
3237 target.createdConfig = config;
3238 }
3239 target.pendingConfigChanges |= configChanges;
3240 }
3241 }
3242
Romain Guy65b345f2011-07-27 18:51:50 -07003243 private void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 // If we are getting ready to gc after going to the background, well
3245 // we are back active so skip it.
3246 unscheduleGcIdler();
3247
3248 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003249 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07003250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 // First: make sure we have the most recent configuration and most
3252 // recent version of the activity, or skip it if some previous call
3253 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003254 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 int N = mRelaunchingActivities.size();
3256 IBinder token = tmp.token;
3257 tmp = null;
3258 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003259 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 if (r.token == token) {
3261 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003262 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 mRelaunchingActivities.remove(i);
3264 i--;
3265 N--;
3266 }
3267 }
Bob Leee5408332009-09-04 18:31:17 -07003268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003270 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 return;
3272 }
Bob Leee5408332009-09-04 18:31:17 -07003273
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003274 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
3275 + tmp.token + " with configChanges=0x"
3276 + Integer.toHexString(configChanges));
3277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 if (mPendingConfiguration != null) {
3279 changedConfig = mPendingConfiguration;
3280 mPendingConfiguration = null;
3281 }
3282 }
Bob Leee5408332009-09-04 18:31:17 -07003283
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003284 if (tmp.createdConfig != null) {
3285 // If the activity manager is passing us its current config,
3286 // assume that is really what we want regardless of what we
3287 // may have pending.
3288 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003289 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
3290 && mConfiguration.diff(tmp.createdConfig) != 0)) {
3291 if (changedConfig == null
3292 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
3293 changedConfig = tmp.createdConfig;
3294 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003295 }
3296 }
3297
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003298 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003299 + tmp.token + ": changedConfig=" + changedConfig);
3300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 // If there was a pending configuration change, execute it first.
3302 if (changedConfig != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003303 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 }
Bob Leee5408332009-09-04 18:31:17 -07003305
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003306 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003307 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 if (r == null) {
3309 return;
3310 }
Bob Leee5408332009-09-04 18:31:17 -07003311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003313 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003314 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003315
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003316 r.activity.mChangingConfigurations = true;
3317
Dianne Hackborne2b04802010-12-09 09:24:55 -08003318 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08003320 performPauseActivity(r.token, false, r.isPreHoneycomb());
3321 }
3322 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
3323 r.state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04003324 r.state.setAllowFds(false);
Dianne Hackborne2b04802010-12-09 09:24:55 -08003325 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 }
Bob Leee5408332009-09-04 18:31:17 -07003327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 r.activity = null;
3331 r.window = null;
3332 r.hideForNow = false;
3333 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003334 // Merge any pending results and pending intents; don't just replace them
3335 if (tmp.pendingResults != null) {
3336 if (r.pendingResults == null) {
3337 r.pendingResults = tmp.pendingResults;
3338 } else {
3339 r.pendingResults.addAll(tmp.pendingResults);
3340 }
3341 }
3342 if (tmp.pendingIntents != null) {
3343 if (r.pendingIntents == null) {
3344 r.pendingIntents = tmp.pendingIntents;
3345 } else {
3346 r.pendingIntents.addAll(tmp.pendingIntents);
3347 }
3348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07003350
Christopher Tateb70f3df2009-04-07 16:07:59 -07003351 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 }
3353
Romain Guy65b345f2011-07-27 18:51:50 -07003354 private void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003355 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 Bitmap thumbnail = createThumbnailBitmap(r);
3357 CharSequence description = null;
3358 try {
3359 description = r.activity.onCreateDescription();
3360 } catch (Exception e) {
3361 if (!mInstrumentation.onException(r.activity, e)) {
3362 throw new RuntimeException(
3363 "Unable to create description of activity "
3364 + r.intent.getComponent().toShortString()
3365 + ": " + e.toString(), e);
3366 }
3367 }
3368 //System.out.println("Reporting top thumbnail " + thumbnail);
3369 try {
3370 ActivityManagerNative.getDefault().reportThumbnail(
3371 token, thumbnail, description);
3372 } catch (RemoteException ex) {
3373 }
3374 }
3375
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003376 ArrayList<ComponentCallbacks2> collectComponentCallbacksLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003378 ArrayList<ComponentCallbacks2> callbacks
3379 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07003380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003382 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003384 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 Activity a = ar.activity;
3386 if (a != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003387 Configuration thisConfig = applyConfigCompatMainThread(newConfig,
3388 ar.packageInfo.mCompatibilityInfo.getIfNeeded());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 if (!ar.activity.mFinished && (allActivities ||
3390 (a != null && !ar.paused))) {
3391 // If the activity is currently resumed, its configuration
3392 // needs to change right now.
3393 callbacks.add(a);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003394 } else if (thisConfig != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 // Otherwise, we will tell it about the change
3396 // the next time it is resumed or shown. Note that
3397 // the activity manager may, before then, decide the
3398 // activity needs to be destroyed to handle its new
3399 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003400 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003401 + ar.activityInfo.name + " newConfig=" + thisConfig);
3402 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 }
3404 }
3405 }
3406 }
3407 if (mServices.size() > 0) {
3408 Iterator<Service> it = mServices.values().iterator();
3409 while (it.hasNext()) {
3410 callbacks.add(it.next());
3411 }
3412 }
3413 synchronized (mProviderMap) {
3414 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003415 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 while (it.hasNext()) {
3417 callbacks.add(it.next().mLocalProvider);
3418 }
3419 }
3420 }
3421 final int N = mAllApplications.size();
3422 for (int i=0; i<N; i++) {
3423 callbacks.add(mAllApplications.get(i));
3424 }
Bob Leee5408332009-09-04 18:31:17 -07003425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 return callbacks;
3427 }
Bob Leee5408332009-09-04 18:31:17 -07003428
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003429 private final void performConfigurationChanged(
3430 ComponentCallbacks2 cb, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 // Only for Activity objects, check that they actually call up to their
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003432 // superclass implementation. ComponentCallbacks2 is an interface, so
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 // we check the runtime type and act accordingly.
3434 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3435 if (activity != null) {
3436 activity.mCalled = false;
3437 }
Bob Leee5408332009-09-04 18:31:17 -07003438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 boolean shouldChangeConfig = false;
3440 if ((activity == null) || (activity.mCurrentConfig == null)) {
3441 shouldChangeConfig = true;
3442 } else {
Bob Leee5408332009-09-04 18:31:17 -07003443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 // If the new config is the same as the config this Activity
3445 // is already running with then don't bother calling
3446 // onConfigurationChanged
3447 int diff = activity.mCurrentConfig.diff(config);
3448 if (diff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 // If this activity doesn't handle any of the config changes
3450 // then don't bother calling onConfigurationChanged as we're
3451 // going to destroy it.
Dianne Hackborne6676352011-06-01 16:51:20 -07003452 if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 shouldChangeConfig = true;
3454 }
3455 }
3456 }
Bob Leee5408332009-09-04 18:31:17 -07003457
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003458 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003459 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 if (shouldChangeConfig) {
3461 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 if (activity != null) {
3464 if (!activity.mCalled) {
3465 throw new SuperNotCalledException(
3466 "Activity " + activity.getLocalClassName() +
3467 " did not call through to super.onConfigurationChanged()");
3468 }
3469 activity.mConfigChangeFlags = 0;
3470 activity.mCurrentConfig = new Configuration(config);
3471 }
3472 }
3473 }
3474
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003475 public final void applyConfigurationToResources(Configuration config) {
3476 synchronized (mPackages) {
3477 applyConfigurationToResourcesLocked(config, null);
3478 }
3479 }
3480
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003481 final boolean applyConfigurationToResourcesLocked(Configuration config,
3482 CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003483 if (mResConfiguration == null) {
3484 mResConfiguration = new Configuration();
3485 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003486 if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003487 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003488 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003489 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003490 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003491 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003492 DisplayMetrics dm = getDisplayMetricsLocked(null, true);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003493
3494 if (compat != null && (mResCompatibilityInfo == null ||
3495 !mResCompatibilityInfo.equals(compat))) {
3496 mResCompatibilityInfo = compat;
3497 changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT
3498 | ActivityInfo.CONFIG_SCREEN_SIZE
3499 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3500 }
Bob Leee5408332009-09-04 18:31:17 -07003501
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003502 // set it for java, this also affects newly created Resources
3503 if (config.locale != null) {
3504 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 }
Bob Leee5408332009-09-04 18:31:17 -07003506
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003507 Resources.updateSystemConfiguration(config, dm, compat);
Bob Leee5408332009-09-04 18:31:17 -07003508
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003509 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003510 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003511
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003512 Iterator<WeakReference<Resources>> it =
3513 mActiveResources.values().iterator();
3514 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3515 // mActiveResources.entrySet().iterator();
3516 while (it.hasNext()) {
3517 WeakReference<Resources> v = it.next();
3518 Resources r = v.get();
3519 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003520 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003521 + r + " config to: " + config);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003522 r.updateConfiguration(config, dm, compat);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003523 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003524 // + " " + r + ": " + r.getConfiguration());
3525 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003526 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003527 it.remove();
3528 }
3529 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003530
3531 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003532 }
Dianne Hackborn836e2622011-10-04 18:32:39 -07003533
3534 final Configuration applyCompatConfiguration() {
3535 Configuration config = mConfiguration;
3536 if (mCompatConfiguration == null) {
3537 mCompatConfiguration = new Configuration();
3538 }
3539 mCompatConfiguration.setTo(mConfiguration);
3540 if (mResCompatibilityInfo != null && !mResCompatibilityInfo.supportsScreen()) {
3541 mResCompatibilityInfo.applyToConfiguration(mCompatConfiguration);
3542 config = mCompatConfiguration;
3543 }
3544 return config;
3545 }
3546
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003547 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003548
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003549 ArrayList<ComponentCallbacks2> callbacks = null;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003550
3551 synchronized (mPackages) {
3552 if (mPendingConfiguration != null) {
3553 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3554 config = mPendingConfiguration;
3555 }
3556 mPendingConfiguration = null;
3557 }
3558
3559 if (config == null) {
3560 return;
3561 }
3562
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003563 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003564 + config);
3565
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003566 applyConfigurationToResourcesLocked(config, compat);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 if (mConfiguration == null) {
3569 mConfiguration = new Configuration();
3570 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003571 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003572 return;
3573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 mConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003575 config = applyCompatConfiguration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 callbacks = collectComponentCallbacksLocked(false, config);
3577 }
Romain Guy65b345f2011-07-27 18:51:50 -07003578
3579 // Cleanup hardware accelerated stuff
3580 WindowManagerImpl.getDefault().trimLocalMemory();
Bob Leee5408332009-09-04 18:31:17 -07003581
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003582 if (callbacks != null) {
3583 final int N = callbacks.size();
3584 for (int i=0; i<N; i++) {
3585 performConfigurationChanged(callbacks.get(i), config);
3586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 }
3588 }
3589
3590 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003591 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 if (r == null || r.activity == null) {
3593 return;
3594 }
Bob Leee5408332009-09-04 18:31:17 -07003595
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003596 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003597 + r.activityInfo.name);
3598
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003599 performConfigurationChanged(r.activity, mCompatConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 }
3601
Romain Guy7eabe552011-07-21 14:56:34 -07003602 final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003603 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003604 try {
Romain Guy7eabe552011-07-21 14:56:34 -07003605 switch (profileType) {
3606 case 1:
3607 ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor());
3608 break;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003609 default:
3610 mProfiler.setProfiler(pcd.path, pcd.fd);
3611 mProfiler.autoStopProfiler = false;
3612 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003613 break;
3614 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003615 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003616 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003617 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003618 } finally {
3619 try {
3620 pcd.fd.close();
3621 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003622 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003623 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003624 }
3625 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07003626 switch (profileType) {
3627 case 1:
3628 ViewDebug.stopLooperProfiling();
3629 break;
3630 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003631 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003632 break;
Romain Guy7eabe552011-07-21 14:56:34 -07003633 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003634 }
3635 }
Bob Leee5408332009-09-04 18:31:17 -07003636
Andy McFadden824c5102010-07-09 16:26:57 -07003637 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3638 if (managed) {
3639 try {
3640 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3641 } catch (IOException e) {
3642 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3643 + " -- can the process access this path?");
3644 } finally {
3645 try {
3646 dhd.fd.close();
3647 } catch (IOException e) {
3648 Slog.w(TAG, "Failure closing profile fd", e);
3649 }
3650 }
3651 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003652 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003653 }
3654 }
3655
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003656 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3657 boolean hasPkgInfo = false;
3658 if (packages != null) {
3659 for (int i=packages.length-1; i>=0; i--) {
3660 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3661 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003662 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003663 ref = mPackages.get(packages[i]);
3664 if (ref != null && ref.get() != null) {
3665 hasPkgInfo = true;
3666 } else {
3667 ref = mResourcePackages.get(packages[i]);
3668 if (ref != null && ref.get() != null) {
3669 hasPkgInfo = true;
3670 }
3671 }
3672 }
3673 mPackages.remove(packages[i]);
3674 mResourcePackages.remove(packages[i]);
3675 }
3676 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003677 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003678 hasPkgInfo);
3679 }
3680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 final void handleLowMemory() {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003682 ArrayList<ComponentCallbacks2> callbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003684 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 callbacks = collectComponentCallbacksLocked(true, null);
3686 }
Bob Leee5408332009-09-04 18:31:17 -07003687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 final int N = callbacks.size();
3689 for (int i=0; i<N; i++) {
3690 callbacks.get(i).onLowMemory();
3691 }
3692
Chris Tatece229052009-03-25 16:44:52 -07003693 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3694 if (Process.myUid() != Process.SYSTEM_UID) {
3695 int sqliteReleased = SQLiteDatabase.releaseMemory();
3696 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3697 }
Bob Leee5408332009-09-04 18:31:17 -07003698
Mike Reedcaf0df12009-04-27 14:32:05 -04003699 // Ask graphics to free up as much as possible (font/image caches)
3700 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701
3702 BinderInternal.forceGc("mem");
3703 }
3704
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003705 final void handleTrimMemory(int level) {
Romain Guybdf76092011-07-18 15:00:43 -07003706 WindowManagerImpl.getDefault().trimMemory(level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003707 ArrayList<ComponentCallbacks2> callbacks;
3708
3709 synchronized (mPackages) {
3710 callbacks = collectComponentCallbacksLocked(true, null);
3711 }
3712
3713 final int N = callbacks.size();
3714 for (int i=0; i<N; i++) {
3715 callbacks.get(i).onTrimMemory(level);
3716 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003717 }
3718
Romain Guya9582652011-11-10 14:20:10 -08003719 private void setupGraphicsSupport(LoadedApk info) {
3720 try {
3721 int uid = Process.myUid();
3722 String[] packages = getPackageManager().getPackagesForUid(uid);
3723
3724 // If there are several packages in this application we won't
3725 // initialize the graphics disk caches
3726 if (packages.length == 1) {
3727 ContextImpl appContext = new ContextImpl();
3728 appContext.init(info, null, this);
3729
3730 HardwareRenderer.setupDiskCache(appContext.getCacheDir());
3731 }
3732 } catch (RemoteException e) {
3733 // Ignore
3734 }
3735 }
3736
Romain Guy65b345f2011-07-27 18:51:50 -07003737 private void handleBindApplication(AppBindData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 mBoundApplication = data;
3739 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003740 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003742 mProfiler = new Profiler();
3743 mProfiler.profileFile = data.initProfileFile;
3744 mProfiler.profileFd = data.initProfileFd;
3745 mProfiler.autoStopProfiler = data.initAutoStopProfiler;
3746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003748 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 android.ddm.DdmHandleAppName.setAppName(data.processName);
3750
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003751 if (data.persistent) {
3752 // Persistent processes on low-memory devices do not get to
3753 // use hardware accelerated drawing, since this can add too much
3754 // overhead to the process.
3755 Display display = WindowManagerImpl.getDefault().getDefaultDisplay();
3756 if (!ActivityManager.isHighEndGfx(display)) {
3757 HardwareRenderer.disable(false);
3758 }
3759 }
Romain Guya9582652011-11-10 14:20:10 -08003760
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003761 if (mProfiler.profileFd != null) {
3762 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003763 }
3764
Joe Onoratod630f102011-03-17 18:42:26 -07003765 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
3766 // implementation to use the pool executor. Normally, we use the
3767 // serialized executor as the default. This has to happen in the
3768 // main thread so the main looper is set right.
3769 if (data.appInfo.targetSdkVersion <= 12) {
3770 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
3771 }
3772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 /*
3774 * Before spawning a new process, reset the time zone to be the system time zone.
3775 * This needs to be done because the system time zone could have changed after the
3776 * the spawning of this process. Without doing this this process would have the incorrect
3777 * system time zone.
3778 */
3779 TimeZone.setDefault(null);
3780
3781 /*
3782 * Initialize the default locale in this process for the reasons we set the time zone.
3783 */
3784 Locale.setDefault(data.config.locale);
3785
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003786 /*
3787 * Update the system configuration since its preloaded and might not
3788 * reflect configuration changes. The configuration object passed
3789 * in AppBindData can be safely assumed to be up to date
3790 */
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003791 applyConfigurationToResourcesLocked(data.config, data.compatInfo);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003792 applyCompatConfiguration();
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003793
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003794 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795
Romain Guya9582652011-11-10 14:20:10 -08003796 setupGraphicsSupport(data.info);
3797
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003798 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003799 * For system applications on userdebug/eng builds, log stack
3800 * traces of disk and network access to dropbox for analysis.
3801 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003802 if ((data.appInfo.flags &
3803 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003804 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3805 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003806 }
3807
3808 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003809 * For apps targetting SDK Honeycomb or later, we don't allow
3810 * network usage on the main event loop / UI thread.
3811 *
3812 * Note to those grepping: this is what ultimately throws
3813 * NetworkOnMainThreadException ...
3814 */
3815 if (data.appInfo.targetSdkVersion > 9) {
3816 StrictMode.enableDeathOnNetwork();
3817 }
3818
3819 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003820 * Switch this process to density compatibility mode if needed.
3821 */
3822 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3823 == 0) {
3824 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3825 }
Bob Leee5408332009-09-04 18:31:17 -07003826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3828 // XXX should have option to change the port.
3829 Debug.changeDebugPort(8100);
3830 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003831 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 + " is waiting for the debugger on port 8100...");
3833
3834 IActivityManager mgr = ActivityManagerNative.getDefault();
3835 try {
3836 mgr.showWaitingForDebugger(mAppThread, true);
3837 } catch (RemoteException ex) {
3838 }
3839
3840 Debug.waitForDebugger();
3841
3842 try {
3843 mgr.showWaitingForDebugger(mAppThread, false);
3844 } catch (RemoteException ex) {
3845 }
3846
3847 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003848 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 + " can be debugged on port 8100...");
3850 }
3851 }
3852
Robert Greenwalt434203a2010-10-11 16:00:27 -07003853 /**
3854 * Initialize the default http proxy in this process for the reasons we set the time zone.
3855 */
3856 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08003857 if (b != null) {
3858 // In pre-boot mode (doing initial launch to collect password), not
3859 // all system is up. This includes the connectivity service, so don't
3860 // crash if we can't get it.
3861 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3862 try {
3863 ProxyProperties proxyProperties = service.getProxy();
3864 Proxy.setHttpProxySystemProperty(proxyProperties);
3865 } catch (RemoteException e) {}
3866 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003869 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 appContext.init(data.info, null, this);
3871 InstrumentationInfo ii = null;
3872 try {
3873 ii = appContext.getPackageManager().
3874 getInstrumentationInfo(data.instrumentationName, 0);
3875 } catch (PackageManager.NameNotFoundException e) {
3876 }
3877 if (ii == null) {
3878 throw new RuntimeException(
3879 "Unable to find instrumentation info for: "
3880 + data.instrumentationName);
3881 }
3882
3883 mInstrumentationAppDir = ii.sourceDir;
3884 mInstrumentationAppPackage = ii.packageName;
3885 mInstrumentedAppDir = data.info.getAppDir();
3886
3887 ApplicationInfo instrApp = new ApplicationInfo();
3888 instrApp.packageName = ii.packageName;
3889 instrApp.sourceDir = ii.sourceDir;
3890 instrApp.publicSourceDir = ii.publicSourceDir;
3891 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003892 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003893 LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003895 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 instrContext.init(pi, null, this);
3897
3898 try {
3899 java.lang.ClassLoader cl = instrContext.getClassLoader();
3900 mInstrumentation = (Instrumentation)
3901 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3902 } catch (Exception e) {
3903 throw new RuntimeException(
3904 "Unable to instantiate instrumentation "
3905 + data.instrumentationName + ": " + e.toString(), e);
3906 }
3907
3908 mInstrumentation.init(this, instrContext, appContext,
3909 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3910
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003911 if (mProfiler.profileFile != null && !ii.handleProfiling
3912 && mProfiler.profileFd == null) {
3913 mProfiler.handlingProfiling = true;
3914 File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 file.getParentFile().mkdirs();
3916 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3917 }
3918
3919 try {
3920 mInstrumentation.onCreate(data.instrumentationArgs);
3921 }
3922 catch (Exception e) {
3923 throw new RuntimeException(
3924 "Exception thrown in onCreate() of "
3925 + data.instrumentationName + ": " + e.toString(), e);
3926 }
3927
3928 } else {
3929 mInstrumentation = new Instrumentation();
3930 }
3931
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003932 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08003933 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003934 }
3935
Christopher Tate181fafa2009-05-14 11:12:14 -07003936 // If the app is being launched for full backup or restore, bring it up in
3937 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003938 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 mInitialApplication = app;
3940
Christopher Tate75a99702011-05-18 16:28:19 -07003941 // don't bring up providers in restricted mode; they may depend on the
3942 // app's custom Application class
3943 if (!data.restrictedBackupMode){
3944 List<ProviderInfo> providers = data.providers;
3945 if (providers != null) {
3946 installContentProviders(app, providers);
3947 // For process that contains content providers, we want to
3948 // ensure that the JIT is enabled "at some point".
3949 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
3950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 }
3952
3953 try {
3954 mInstrumentation.callApplicationOnCreate(app);
3955 } catch (Exception e) {
3956 if (!mInstrumentation.onException(app, e)) {
3957 throw new RuntimeException(
3958 "Unable to create application " + app.getClass().getName()
3959 + ": " + e.toString(), e);
3960 }
3961 }
3962 }
3963
3964 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3965 IActivityManager am = ActivityManagerNative.getDefault();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003966 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
3967 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 Debug.stopMethodTracing();
3969 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003970 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 // + ", app thr: " + mAppThread);
3972 try {
3973 am.finishInstrumentation(mAppThread, resultCode, results);
3974 } catch (RemoteException ex) {
3975 }
3976 }
3977
Romain Guy65b345f2011-07-27 18:51:50 -07003978 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979 Context context, List<ProviderInfo> providers) {
3980 final ArrayList<IActivityManager.ContentProviderHolder> results =
3981 new ArrayList<IActivityManager.ContentProviderHolder>();
3982
3983 Iterator<ProviderInfo> i = providers.iterator();
3984 while (i.hasNext()) {
3985 ProviderInfo cpi = i.next();
3986 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003987 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 buf.append(cpi.authority);
3989 buf.append(": ");
3990 buf.append(cpi.name);
3991 Log.i(TAG, buf.toString());
Jeff Brownddaa9ac2011-11-11 20:16:14 -08003992 IContentProvider cp = installProvider(context, null, cpi,
3993 false /*noisy*/, true /*noReleaseNeeded*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 if (cp != null) {
3995 IActivityManager.ContentProviderHolder cph =
Jeff Brownddaa9ac2011-11-11 20:16:14 -08003996 new IActivityManager.ContentProviderHolder(cpi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 cph.provider = cp;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08003998 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 }
4001 }
4002
4003 try {
4004 ActivityManagerNative.getDefault().publishContentProviders(
4005 getApplicationThread(), results);
4006 } catch (RemoteException ex) {
4007 }
4008 }
4009
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004010 public final IContentProvider acquireProvider(Context c, String name) {
4011 IContentProvider provider = acquireExistingProvider(c, name);
4012 if (provider != null) {
4013 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 }
4015
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004016 // There is a possible race here. Another thread may try to acquire
4017 // the same provider at the same time. When this happens, we want to ensure
4018 // that the first one wins.
4019 // Note that we cannot hold the lock while acquiring and installing the
4020 // provider since it might take a long time to run and it could also potentially
4021 // be re-entrant in the case where the provider is in the same process.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 IActivityManager.ContentProviderHolder holder = null;
4023 try {
4024 holder = ActivityManagerNative.getDefault().getContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004025 getApplicationThread(), name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 } catch (RemoteException ex) {
4027 }
4028 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004029 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 return null;
4031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004033 // Install provider will increment the reference count for us, and break
4034 // any ties in the race.
4035 provider = installProvider(c, holder.provider, holder.info,
4036 true /*noisy*/, holder.noReleaseNeeded);
4037 if (holder.provider != null && provider != holder.provider) {
4038 if (localLOGV) {
4039 Slog.v(TAG, "acquireProvider: lost the race, releasing extraneous "
4040 + "reference to the content provider");
4041 }
4042 try {
4043 ActivityManagerNative.getDefault().removeContentProvider(
4044 getApplicationThread(), name);
4045 } catch (RemoteException ex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 }
4047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 return provider;
4049 }
4050
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004051 public final IContentProvider acquireExistingProvider(Context c, String name) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004052 synchronized (mProviderMap) {
4053 ProviderClientRecord pr = mProviderMap.get(name);
4054 if (pr == null) {
4055 return null;
4056 }
4057
4058 IContentProvider provider = pr.mProvider;
4059 IBinder jBinder = provider.asBinder();
4060
4061 // Only increment the ref count if we have one. If we don't then the
4062 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004063 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004064 if (prc != null) {
4065 prc.count += 1;
4066 if (prc.count == 1) {
4067 if (localLOGV) {
4068 Slog.v(TAG, "acquireExistingProvider: "
4069 + "snatched provider from the jaws of death");
4070 }
4071 // Because the provider previously had a reference count of zero,
4072 // it was scheduled to be removed. Cancel that.
4073 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4074 }
4075 }
4076 return provider;
4077 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004078 }
4079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 public final boolean releaseProvider(IContentProvider provider) {
4081 if(provider == null) {
4082 return false;
4083 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004086 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004088 if (prc == null) {
4089 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004091 }
4092
4093 if (prc.count == 0) {
4094 if (localLOGV) Slog.v(TAG, "releaseProvider: ref count already 0, how?");
4095 return false;
4096 }
4097
4098 prc.count -= 1;
4099 if (prc.count == 0) {
4100 // Schedule the actual remove asynchronously, since we don't know the context
4101 // this will be called in.
4102 // TODO: it would be nice to post a delayed message, so
4103 // if we come back and need the same provider quickly
4104 // we will still have it available.
4105 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4106 mH.sendMessage(msg);
4107 }
4108 return true;
4109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 }
4111
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004112 final void completeRemoveProvider(IContentProvider provider) {
4113 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004114 String remoteProviderName = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004115 synchronized(mProviderMap) {
4116 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004117 if (prc == null) {
4118 // Either no release is needed (so we shouldn't be here) or the
4119 // provider was already released.
4120 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: release not needed");
4121 return;
4122 }
4123
4124 if (prc.count != 0) {
4125 // There was a race! Some other client managed to acquire
4126 // the provider before the removal was completed.
4127 // Abort the removal. We will do it later.
4128 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: lost the race, "
4129 + "provider still in use");
4130 return;
4131 }
4132
4133 mProviderRefCountMap.remove(jBinder);
4134
4135 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
4136 while (iter.hasNext()) {
4137 ProviderClientRecord pr = iter.next();
4138 IBinder myBinder = pr.mProvider.asBinder();
4139 if (myBinder == jBinder) {
4140 iter.remove();
4141 if (pr.mLocalProvider == null) {
4142 myBinder.unlinkToDeath(pr, 0);
4143 if (remoteProviderName == null) {
4144 remoteProviderName = pr.mName;
4145 }
4146 }
4147 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004148 }
4149 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004150
4151 if (remoteProviderName != null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004152 try {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004153 if (localLOGV) {
4154 Slog.v(TAG, "removeProvider: Invoking ActivityManagerNative."
4155 + "removeContentProvider(" + remoteProviderName + ")");
4156 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004157 ActivityManagerNative.getDefault().removeContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004158 getApplicationThread(), remoteProviderName);
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004159 } catch (RemoteException e) {
4160 //do nothing content provider object is dead any way
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004161 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004162 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164
4165 final void removeDeadProvider(String name, IContentProvider provider) {
4166 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004167 ProviderClientRecord pr = mProviderMap.get(name);
Jeff Brown2a4c5ac2011-08-23 11:58:26 -07004168 if (pr != null && pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004169 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004170 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004171 if (removed != null) {
4172 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 }
4175 }
4176 }
4177
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004178 /**
4179 * Installs the provider.
4180 *
4181 * Providers that are local to the process or that come from the system server
4182 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
4183 * Other remote providers are reference counted. The initial reference count
4184 * for all reference counted providers is one. Providers that are not reference
4185 * counted do not have a reference count (at all).
4186 *
4187 * This method detects when a provider has already been installed. When this happens,
4188 * it increments the reference count of the existing provider (if appropriate)
4189 * and returns the existing provider. This can happen due to concurrent
4190 * attempts to acquire the same provider.
4191 */
Romain Guy65b345f2011-07-27 18:51:50 -07004192 private IContentProvider installProvider(Context context,
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004193 IContentProvider provider, ProviderInfo info,
4194 boolean noisy, boolean noReleaseNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004195 ContentProvider localProvider = null;
4196 if (provider == null) {
4197 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004198 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 + info.name);
4200 }
4201 Context c = null;
4202 ApplicationInfo ai = info.applicationInfo;
4203 if (context.getPackageName().equals(ai.packageName)) {
4204 c = context;
4205 } else if (mInitialApplication != null &&
4206 mInitialApplication.getPackageName().equals(ai.packageName)) {
4207 c = mInitialApplication;
4208 } else {
4209 try {
4210 c = context.createPackageContext(ai.packageName,
4211 Context.CONTEXT_INCLUDE_CODE);
4212 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07004213 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 }
4215 }
4216 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004217 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 ai.packageName +
4219 " while loading content provider " +
4220 info.name);
4221 return null;
4222 }
4223 try {
4224 final java.lang.ClassLoader cl = c.getClassLoader();
4225 localProvider = (ContentProvider)cl.
4226 loadClass(info.name).newInstance();
4227 provider = localProvider.getIContentProvider();
4228 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004229 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 info.name + " from sourceDir " +
4231 info.applicationInfo.sourceDir);
4232 return null;
4233 }
Joe Onorato43a17652011-04-06 19:22:23 -07004234 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 TAG, "Instantiating local provider " + info.name);
4236 // XXX Need to create the correct context for this provider.
4237 localProvider.attachInfo(c, info);
4238 } catch (java.lang.Exception e) {
4239 if (!mInstrumentation.onException(null, e)) {
4240 throw new RuntimeException(
4241 "Unable to get provider " + info.name
4242 + ": " + e.toString(), e);
4243 }
4244 return null;
4245 }
4246 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004247 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 + info.name);
4249 }
4250
4251 synchronized (mProviderMap) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004252 // There is a possibility that this thread raced with another thread to
4253 // add the provider. If we find another thread got there first then we
4254 // just get out of the way and return the original provider.
4255 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004256 String names[] = PATTERN_SEMICOLON.split(info.authority);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004257 for (int i = 0; i < names.length; i++) {
4258 ProviderClientRecord pr = mProviderMap.get(names[i]);
4259 if (pr != null) {
4260 if (localLOGV) {
4261 Slog.v(TAG, "installProvider: lost the race, "
4262 + "using existing named provider");
4263 }
4264 provider = pr.mProvider;
4265 } else {
4266 pr = new ProviderClientRecord(names[i], provider, localProvider);
4267 if (localProvider == null) {
4268 try {
4269 jBinder.linkToDeath(pr, 0);
4270 } catch (RemoteException e) {
4271 // Provider already dead. Bail out of here without making
4272 // any changes to the provider map or other data structures.
4273 return null;
4274 }
4275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 mProviderMap.put(names[i], pr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 }
4278 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 if (localProvider != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004281 ProviderClientRecord pr = mLocalProviders.get(jBinder);
4282 if (pr != null) {
4283 if (localLOGV) {
4284 Slog.v(TAG, "installProvider: lost the race, "
4285 + "using existing local provider");
4286 }
4287 provider = pr.mProvider;
4288 } else {
4289 pr = new ProviderClientRecord(null, provider, localProvider);
4290 mLocalProviders.put(jBinder, pr);
4291 }
4292 }
4293
4294 if (!noReleaseNeeded) {
4295 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4296 if (prc != null) {
4297 if (localLOGV) {
4298 Slog.v(TAG, "installProvider: lost the race, incrementing ref count");
4299 }
4300 prc.count += 1;
4301 if (prc.count == 1) {
4302 if (localLOGV) {
4303 Slog.v(TAG, "installProvider: "
4304 + "snatched provider from the jaws of death");
4305 }
4306 // Because the provider previously had a reference count of zero,
4307 // it was scheduled to be removed. Cancel that.
4308 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4309 }
4310 } else {
4311 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 }
4314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 return provider;
4316 }
4317
Romain Guy65b345f2011-07-27 18:51:50 -07004318 private void attach(boolean system) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 sThreadLocal.set(this);
4320 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07004322 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004323 public void run() {
4324 ensureJitEnabled();
4325 }
4326 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4328 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4329 IActivityManager mgr = ActivityManagerNative.getDefault();
4330 try {
4331 mgr.attachApplication(mAppThread);
4332 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07004333 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 }
4335 } else {
4336 // Don't set application object here -- if the system crashes,
4337 // we can't display an alert, we just want to die die die.
4338 android.ddm.DdmHandleAppName.setAppName("system_process");
4339 try {
4340 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08004341 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 context.init(getSystemContext().mPackageInfo, null, this);
4343 Application app = Instrumentation.newApplication(Application.class, context);
4344 mAllApplications.add(app);
4345 mInitialApplication = app;
4346 app.onCreate();
4347 } catch (Exception e) {
4348 throw new RuntimeException(
4349 "Unable to instantiate Application():" + e.toString(), e);
4350 }
4351 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004352
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004353 ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004354 public void onConfigurationChanged(Configuration newConfig) {
4355 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004356 // We need to apply this change to the resources
4357 // immediately, because upon returning the view
4358 // hierarchy will be informed about it.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004359 if (applyConfigurationToResourcesLocked(newConfig, null)) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004360 // This actually changed the resources! Tell
4361 // everyone about it.
4362 if (mPendingConfiguration == null ||
4363 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
4364 mPendingConfiguration = newConfig;
4365
4366 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
4367 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004368 }
4369 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004370 }
4371 public void onLowMemory() {
4372 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004373 public void onTrimMemory(int level) {
4374 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004375 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 }
4377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 public static final ActivityThread systemMain() {
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004379 HardwareRenderer.disable(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 ActivityThread thread = new ActivityThread();
4381 thread.attach(true);
4382 return thread;
4383 }
4384
Jeff Brown10e89712011-07-08 18:52:57 -07004385 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07004387 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 }
4389 }
4390
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004391 public int getIntCoreSetting(String key, int defaultValue) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004392 synchronized (mPackages) {
4393 if (mCoreSettings != null) {
4394 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004395 } else {
4396 return defaultValue;
4397 }
4398 }
4399 }
4400
Romain Guy65b345f2011-07-27 18:51:50 -07004401 public static void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004402 SamplingProfilerIntegration.start();
4403
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08004404 // CloseGuard defaults to true and can be quite spammy. We
4405 // disable it here, but selectively enable it later (via
4406 // StrictMode) on debug builds, but using DropBox, not logs.
4407 CloseGuard.setEnabled(false);
4408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 Process.setArgV0("<pre-initialized>");
4410
4411 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004412 if (sMainThreadHandler == null) {
4413 sMainThreadHandler = new Handler();
4414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004415
4416 ActivityThread thread = new ActivityThread();
4417 thread.attach(false);
4418
Dianne Hackborn287952c2010-09-22 22:34:31 -07004419 if (false) {
4420 Looper.myLooper().setMessageLogging(new
4421 LogPrinter(Log.DEBUG, "ActivityThread"));
4422 }
4423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 Looper.loop();
4425
Jeff Brown10e89712011-07-08 18:52:57 -07004426 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 }
4428}