blob: bac3c6c4b8356a8eb5703d9a753f6432afd8908b [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;
Jeff Brown6754ba22011-12-14 20:20:01 -080068import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080069import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.Display;
Romain Guy52339202010-09-03 16:04:46 -070071import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.view.View;
73import android.view.ViewDebug;
74import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -070075import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.view.Window;
77import android.view.WindowManager;
78import android.view.WindowManagerImpl;
79
80import com.android.internal.os.BinderInternal;
81import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070082import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
84import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
85
86import java.io.File;
87import java.io.FileDescriptor;
88import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070089import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import java.io.PrintWriter;
91import java.lang.ref.WeakReference;
Robert Greenwalt03595d02010-11-02 14:08:23 -070092import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import java.util.ArrayList;
94import java.util.HashMap;
95import java.util.Iterator;
96import java.util.List;
97import java.util.Locale;
98import java.util.Map;
99import java.util.TimeZone;
100import java.util.regex.Pattern;
101
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -0800102import dalvik.system.CloseGuard;
Bob Leee5408332009-09-04 18:31:17 -0700103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104final class SuperNotCalledException extends AndroidRuntimeException {
105 public SuperNotCalledException(String msg) {
106 super(msg);
107 }
108}
109
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700110final class RemoteServiceException extends AndroidRuntimeException {
111 public RemoteServiceException(String msg) {
112 super(msg);
113 }
114}
115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116/**
117 * This manages the execution of the main thread in an
118 * application process, scheduling and executing activities,
119 * broadcasts, and other operations on it as the activity
120 * manager requests.
121 *
122 * {@hide}
123 */
124public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700125 /** @hide */
126 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700127 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700128 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700129 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700130 /** @hide */
131 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700132 private static final boolean DEBUG_RESULTS = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700133 private static final boolean DEBUG_BACKUP = true;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700134 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
136 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
137 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
138 private static final int LOG_ON_PAUSE_CALLED = 30021;
139 private static final int LOG_ON_RESUME_CALLED = 30022;
140
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700141 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700142
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700143 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700145 final ApplicationThread mAppThread = new ApplicationThread();
146 final Looper mLooper = Looper.myLooper();
147 final H mH = new H();
148 final HashMap<IBinder, ActivityClientRecord> mActivities
149 = new HashMap<IBinder, ActivityClientRecord>();
150 // List of new activities (via ActivityRecord.nextIdle) that should
151 // be reported when next we idle.
152 ActivityClientRecord mNewActivities = null;
153 // Number of activities that are currently visible on-screen.
154 int mNumVisibleActivities = 0;
155 final HashMap<IBinder, Service> mServices
156 = new HashMap<IBinder, Service>();
157 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700158 Profiler mProfiler;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700159 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700160 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700161 Configuration mResConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700162 CompatibilityInfo mResCompatibilityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700163 Application mInitialApplication;
164 final ArrayList<Application> mAllApplications
165 = new ArrayList<Application>();
166 // set of instantiated backup agents, keyed by package name
167 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Romain Guy65b345f2011-07-27 18:51:50 -0700168 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal<ActivityThread>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700169 Instrumentation mInstrumentation;
170 String mInstrumentationAppDir = null;
171 String mInstrumentationAppPackage = null;
172 String mInstrumentedAppDir = null;
173 boolean mSystemThread = false;
174 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700176 // These can be accessed by multiple threads; mPackages is the lock.
177 // XXX For now we keep around information about all packages we have
178 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800179 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700180 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800181 // which means this lock gets held while the activity and window managers
182 // holds their own lock. Thus you MUST NEVER call back into the activity manager
183 // or window manager or anything that depends on them while holding this lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700184 final HashMap<String, WeakReference<LoadedApk>> mPackages
185 = new HashMap<String, WeakReference<LoadedApk>>();
186 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
187 = new HashMap<String, WeakReference<LoadedApk>>();
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700188 final HashMap<CompatibilityInfo, DisplayMetrics> mDisplayMetrics
189 = new HashMap<CompatibilityInfo, DisplayMetrics>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700190 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
191 = new HashMap<ResourcesKey, WeakReference<Resources> >();
192 final ArrayList<ActivityClientRecord> mRelaunchingActivities
193 = new ArrayList<ActivityClientRecord>();
194 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700196 // The lock of mProviderMap protects the following variables.
197 final HashMap<String, ProviderClientRecord> mProviderMap
198 = new HashMap<String, ProviderClientRecord>();
199 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
200 = new HashMap<IBinder, ProviderRefCount>();
201 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
202 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Jeff Hamilton52d32032011-01-08 15:31:26 -0600204 final HashMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
205 = new HashMap<Activity, ArrayList<OnActivityPausedListener>>();
206
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700207 final GcIdler mGcIdler = new GcIdler();
208 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700210 static Handler sMainThreadHandler; // set once in main()
211
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800212 Bundle mCoreSettings = null;
213
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400214 static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700216 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 Intent intent;
218 Bundle state;
219 Activity activity;
220 Window window;
221 Activity parent;
222 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700223 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 boolean paused;
225 boolean stopped;
226 boolean hideForNow;
227 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700228 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700229 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700231 String profileFile;
232 ParcelFileDescriptor profileFd;
233 boolean autoStopProfiler;
234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400236 CompatibilityInfo compatInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700237 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
239 List<ResultInfo> pendingResults;
240 List<Intent> pendingIntents;
241
242 boolean startsNotResumed;
243 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800244 int pendingConfigChanges;
245 boolean onlyLocalRequest;
246
247 View mPendingRemoveWindow;
248 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700250 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 parent = null;
252 embeddedID = null;
253 paused = false;
254 stopped = false;
255 hideForNow = false;
256 nextIdle = null;
257 }
258
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800259 public boolean isPreHoneycomb() {
260 if (activity != null) {
261 return activity.getApplicationInfo().targetSdkVersion
262 < android.os.Build.VERSION_CODES.HONEYCOMB;
263 }
264 return false;
265 }
266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 public String toString() {
268 ComponentName componentName = intent.getComponent();
269 return "ActivityRecord{"
270 + Integer.toHexString(System.identityHashCode(this))
271 + " token=" + token + " " + (componentName == null
272 ? "no component name" : componentName.toShortString())
273 + "}";
274 }
275 }
276
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400277 final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 final String mName;
279 final IContentProvider mProvider;
280 final ContentProvider mLocalProvider;
281
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700282 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 ContentProvider localProvider) {
284 mName = name;
285 mProvider = provider;
286 mLocalProvider = localProvider;
287 }
288
289 public void binderDied() {
290 removeDeadProvider(mName, mProvider);
291 }
292 }
293
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400294 static final class NewIntentData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 List<Intent> intents;
296 IBinder token;
297 public String toString() {
298 return "NewIntentData{intents=" + intents + " token=" + token + "}";
299 }
300 }
301
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400302 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700303 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
304 boolean ordered, boolean sticky, IBinder token) {
305 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
306 this.intent = intent;
307 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 Intent intent;
310 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400311 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 public String toString() {
313 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700314 info.packageName + " resultCode=" + getResultCode()
315 + " resultData=" + getResultData() + " resultExtras="
316 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 }
318 }
319
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400320 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700321 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400322 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700323 int backupMode;
324 public String toString() {
325 return "CreateBackupAgentData{appInfo=" + appInfo
326 + " backupAgent=" + appInfo.backupAgentName
327 + " mode=" + backupMode + "}";
328 }
329 }
Bob Leee5408332009-09-04 18:31:17 -0700330
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400331 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 IBinder token;
333 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400334 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 Intent intent;
336 public String toString() {
337 return "CreateServiceData{token=" + token + " className="
338 + info.name + " packageName=" + info.packageName
339 + " intent=" + intent + "}";
340 }
341 }
342
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400343 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 IBinder token;
345 Intent intent;
346 boolean rebind;
347 public String toString() {
348 return "BindServiceData{token=" + token + " intent=" + intent + "}";
349 }
350 }
351
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400352 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700354 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700356 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 Intent args;
358 public String toString() {
359 return "ServiceArgsData{token=" + token + " startId=" + startId
360 + " args=" + args + "}";
361 }
362 }
363
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400364 static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700365 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 String processName;
367 ApplicationInfo appInfo;
368 List<ProviderInfo> providers;
369 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 Bundle instrumentationArgs;
371 IInstrumentationWatcher instrumentationWatcher;
372 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700373 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700374 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400376 CompatibilityInfo compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700377
378 /** Initial values for {@link Profiler}. */
379 String initProfileFile;
380 ParcelFileDescriptor initProfileFd;
381 boolean initAutoStopProfiler;
382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 public String toString() {
384 return "AppBindData{appInfo=" + appInfo + "}";
385 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700386 }
387
388 static final class Profiler {
389 String profileFile;
390 ParcelFileDescriptor profileFd;
391 boolean autoStopProfiler;
392 boolean profiling;
393 boolean handlingProfiling;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700394 public void setProfiler(String file, ParcelFileDescriptor fd) {
395 if (profiling) {
396 if (fd != null) {
397 try {
398 fd.close();
399 } catch (IOException e) {
400 }
401 }
402 return;
403 }
404 if (profileFd != null) {
405 try {
406 profileFd.close();
407 } catch (IOException e) {
408 }
409 }
410 profileFile = file;
411 profileFd = fd;
412 }
413 public void startProfiling() {
414 if (profileFd == null || profiling) {
415 return;
416 }
417 try {
418 Debug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
419 8 * 1024 * 1024, 0);
420 profiling = true;
421 } catch (RuntimeException e) {
422 Slog.w(TAG, "Profiling failed on path " + profileFile);
423 try {
424 profileFd.close();
425 profileFd = null;
426 } catch (IOException e2) {
427 Slog.w(TAG, "Failure closing profile fd", e2);
428 }
429 }
430 }
431 public void stopProfiling() {
432 if (profiling) {
433 profiling = false;
434 Debug.stopMethodTracing();
435 if (profileFd != null) {
436 try {
437 profileFd.close();
438 } catch (IOException e) {
439 }
440 }
441 profileFd = null;
442 profileFile = null;
443 }
444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 }
446
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400447 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700448 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700449 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800450 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 }
453
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454 static final class ResultData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 IBinder token;
456 List<ResultInfo> results;
457 public String toString() {
458 return "ResultData{token=" + token + " results" + results + "}";
459 }
460 }
461
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400462 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800463 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 String what;
465 String who;
466 }
467
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400468 static final class ProfilerControlData {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700469 String path;
470 ParcelFileDescriptor fd;
471 }
472
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400473 static final class DumpHeapData {
Andy McFadden824c5102010-07-09 16:26:57 -0700474 String path;
475 ParcelFileDescriptor fd;
476 }
477
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400478 static final class UpdateCompatibilityData {
479 String pkg;
480 CompatibilityInfo info;
481 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -0700482
Romain Guy65b345f2011-07-27 18:51:50 -0700483 private native void dumpGraphicsInfo(FileDescriptor fd);
Chet Haase9c1e23b2011-03-24 10:51:31 -0700484
Romain Guy65b345f2011-07-27 18:51:50 -0700485 private class ApplicationThread extends ApplicationThreadNative {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700486 private static final String HEAP_COLUMN = "%13s %8s %8s %8s %8s %8s %8s";
487 private static final String ONE_COUNT_COLUMN = "%21s %8d";
488 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
489 private static final String TWO_COUNT_COLUMNS_DB = "%21s %8d %21s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700490 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 // Formatting for checkin service - update version if row format changes
493 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700494
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700495 private void updatePendingConfiguration(Configuration config) {
496 synchronized (mPackages) {
497 if (mPendingConfiguration == null ||
498 mPendingConfiguration.isOtherSeqNewer(config)) {
499 mPendingConfiguration = config;
500 }
501 }
502 }
503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 public final void schedulePauseActivity(IBinder token, boolean finished,
505 boolean userLeaving, int configChanges) {
506 queueOrSendMessage(
507 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
508 token,
509 (userLeaving ? 1 : 0),
510 configChanges);
511 }
512
513 public final void scheduleStopActivity(IBinder token, boolean showWindow,
514 int configChanges) {
515 queueOrSendMessage(
516 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
517 token, 0, configChanges);
518 }
519
520 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
521 queueOrSendMessage(
522 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
523 token);
524 }
525
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800526 public final void scheduleSleeping(IBinder token, boolean sleeping) {
527 queueOrSendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
528 }
529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
531 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
532 }
533
534 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
535 ResultData res = new ResultData();
536 res.token = token;
537 res.results = results;
538 queueOrSendMessage(H.SEND_RESULT, res);
539 }
540
541 // we use token to identify this activity without having to send the
542 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700543 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700544 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
545 Bundle state, List<ResultInfo> pendingResults,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700546 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
547 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700548 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549
550 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700551 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 r.intent = intent;
553 r.activityInfo = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400554 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 r.state = state;
556
557 r.pendingResults = pendingResults;
558 r.pendingIntents = pendingNewIntents;
559
560 r.startsNotResumed = notResumed;
561 r.isForward = isForward;
562
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700563 r.profileFile = profileName;
564 r.profileFd = profileFd;
565 r.autoStopProfiler = autoStopProfiler;
566
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700567 updatePendingConfiguration(curConfig);
568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
570 }
571
572 public final void scheduleRelaunchActivity(IBinder token,
573 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800574 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800575 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
576 configChanges, notResumed, config, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 }
578
579 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
580 NewIntentData data = new NewIntentData();
581 data.intents = intents;
582 data.token = token;
583
584 queueOrSendMessage(H.NEW_INTENT, data);
585 }
586
587 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
588 int configChanges) {
589 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
590 configChanges);
591 }
592
593 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400594 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
595 boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700596 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
597 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400599 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 queueOrSendMessage(H.RECEIVER, r);
601 }
602
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400603 public final void scheduleCreateBackupAgent(ApplicationInfo app,
604 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700605 CreateBackupAgentData d = new CreateBackupAgentData();
606 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400607 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700608 d.backupMode = backupMode;
609
610 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
611 }
612
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400613 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
614 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700615 CreateBackupAgentData d = new CreateBackupAgentData();
616 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400617 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700618
619 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
620 }
621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 public final void scheduleCreateService(IBinder token,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400623 ServiceInfo info, CompatibilityInfo compatInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 CreateServiceData s = new CreateServiceData();
625 s.token = token;
626 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400627 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628
629 queueOrSendMessage(H.CREATE_SERVICE, s);
630 }
631
632 public final void scheduleBindService(IBinder token, Intent intent,
633 boolean rebind) {
634 BindServiceData s = new BindServiceData();
635 s.token = token;
636 s.intent = intent;
637 s.rebind = rebind;
638
639 queueOrSendMessage(H.BIND_SERVICE, s);
640 }
641
642 public final void scheduleUnbindService(IBinder token, Intent intent) {
643 BindServiceData s = new BindServiceData();
644 s.token = token;
645 s.intent = intent;
646
647 queueOrSendMessage(H.UNBIND_SERVICE, s);
648 }
649
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700650 public final void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700651 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 ServiceArgsData s = new ServiceArgsData();
653 s.token = token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700654 s.taskRemoved = taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700656 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 s.args = args;
658
659 queueOrSendMessage(H.SERVICE_ARGS, s);
660 }
661
662 public final void scheduleStopService(IBinder token) {
663 queueOrSendMessage(H.STOP_SERVICE, token);
664 }
665
666 public final void bindApplication(String processName,
667 ApplicationInfo appInfo, List<ProviderInfo> providers,
668 ComponentName instrumentationName, String profileFile,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700669 ParcelFileDescriptor profileFd, boolean autoStopProfiler,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700671 int debugMode, boolean isRestrictedBackupMode, boolean persistent,
672 Configuration config, CompatibilityInfo compatInfo,
673 Map<String, IBinder> services, Bundle coreSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674
675 if (services != null) {
676 // Setup the service cache in the ServiceManager
677 ServiceManager.initServiceCache(services);
678 }
679
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800680 setCoreSettings(coreSettings);
681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 AppBindData data = new AppBindData();
683 data.processName = processName;
684 data.appInfo = appInfo;
685 data.providers = providers;
686 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 data.instrumentationArgs = instrumentationArgs;
688 data.instrumentationWatcher = instrumentationWatcher;
689 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700690 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700691 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400693 data.compatInfo = compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700694 data.initProfileFile = profileFile;
695 data.initProfileFd = profileFd;
696 data.initAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 queueOrSendMessage(H.BIND_APPLICATION, data);
698 }
699
700 public final void scheduleExit() {
701 queueOrSendMessage(H.EXIT_APPLICATION, null);
702 }
703
Christopher Tate5e1ab332009-09-01 20:32:49 -0700704 public final void scheduleSuicide() {
705 queueOrSendMessage(H.SUICIDE, null);
706 }
707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 public void requestThumbnail(IBinder token) {
709 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
710 }
711
712 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700713 updatePendingConfiguration(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
715 }
716
717 public void updateTimeZone() {
718 TimeZone.setDefault(null);
719 }
720
Robert Greenwalt03595d02010-11-02 14:08:23 -0700721 public void clearDnsCache() {
722 // a non-standard API to get this to libcore
723 InetAddress.clearDnsCache();
724 }
725
Robert Greenwalt434203a2010-10-11 16:00:27 -0700726 public void setHttpProxy(String host, String port, String exclList) {
727 Proxy.setHttpProxySystemProperty(host, port, exclList);
728 }
729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 public void processInBackground() {
731 mH.removeMessages(H.GC_WHEN_IDLE);
732 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
733 }
734
735 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700736 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700737 try {
738 data.fd = ParcelFileDescriptor.dup(fd);
739 data.token = servicetoken;
740 data.args = args;
741 queueOrSendMessage(H.DUMP_SERVICE, data);
742 } catch (IOException e) {
743 Slog.w(TAG, "dumpService failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 }
745 }
746
747 // This function exists to make sure all receiver dispatching is
748 // correctly ordered, since these are one-way calls and the binder driver
749 // applies transaction ordering per object for such calls.
750 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700751 int resultCode, String dataStr, Bundle extras, boolean ordered,
752 boolean sticky) throws RemoteException {
753 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 }
Bob Leee5408332009-09-04 18:31:17 -0700755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 public void scheduleLowMemory() {
757 queueOrSendMessage(H.LOW_MEMORY, null);
758 }
759
760 public void scheduleActivityConfigurationChanged(IBinder token) {
761 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
762 }
763
Romain Guy7eabe552011-07-21 14:56:34 -0700764 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd,
765 int profileType) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700766 ProfilerControlData pcd = new ProfilerControlData();
767 pcd.path = path;
768 pcd.fd = fd;
Romain Guy7eabe552011-07-21 14:56:34 -0700769 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800770 }
771
Andy McFadden824c5102010-07-09 16:26:57 -0700772 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
773 DumpHeapData dhd = new DumpHeapData();
774 dhd.path = path;
775 dhd.fd = fd;
776 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
777 }
778
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700779 public void setSchedulingGroup(int group) {
780 // Note: do this immediately, since going into the foreground
781 // should happen regardless of what pending work we have to do
782 // and the activity manager will wait for us to report back that
783 // we are done before sending us to the background.
784 try {
785 Process.setProcessGroup(Process.myPid(), group);
786 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800787 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700788 }
789 }
Bob Leee5408332009-09-04 18:31:17 -0700790
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700791 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
792 Debug.getMemoryInfo(outInfo);
793 }
Bob Leee5408332009-09-04 18:31:17 -0700794
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700795 public void dispatchPackageBroadcast(int cmd, String[] packages) {
796 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
797 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700798
799 public void scheduleCrash(String msg) {
800 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
801 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700802
Dianne Hackborn30d71892010-12-11 10:37:55 -0800803 public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
804 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700805 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700806 try {
807 data.fd = ParcelFileDescriptor.dup(fd);
808 data.token = activitytoken;
809 data.prefix = prefix;
810 data.args = args;
811 queueOrSendMessage(H.DUMP_ACTIVITY, data);
812 } catch (IOException e) {
813 Slog.w(TAG, "dumpActivity failed", e);
Dianne Hackborn625ac272010-09-17 18:29:22 -0700814 }
815 }
Chet Haase9c1e23b2011-03-24 10:51:31 -0700816
Marco Nelissen18cb2872011-11-15 11:19:53 -0800817 public void dumpProvider(FileDescriptor fd, IBinder providertoken,
818 String[] args) {
819 DumpComponentInfo data = new DumpComponentInfo();
820 try {
821 data.fd = ParcelFileDescriptor.dup(fd);
822 data.token = providertoken;
823 data.args = args;
824 queueOrSendMessage(H.DUMP_PROVIDER, data);
825 } catch (IOException e) {
826 Slog.w(TAG, "dumpProvider failed", e);
827 }
828 }
829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 @Override
Dianne Hackbornb437e092011-08-05 17:50:29 -0700831 public Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, boolean checkin,
832 boolean all, String[] args) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700833 FileOutputStream fout = new FileOutputStream(fd);
834 PrintWriter pw = new PrintWriter(fout);
835 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -0700836 return dumpMemInfo(pw, checkin, all, args);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700837 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -0700838 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -0700839 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700840 }
841
Dianne Hackbornb437e092011-08-05 17:50:29 -0700842 private Debug.MemoryInfo dumpMemInfo(PrintWriter pw, boolean checkin, boolean all,
843 String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 long nativeMax = Debug.getNativeHeapSize() / 1024;
845 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
846 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
847
848 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
849 Debug.getMemoryInfo(memInfo);
850
Dianne Hackbornb437e092011-08-05 17:50:29 -0700851 if (!all) {
852 return memInfo;
853 }
854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 Runtime runtime = Runtime.getRuntime();
856
857 long dalvikMax = runtime.totalMemory() / 1024;
858 long dalvikFree = runtime.freeMemory() / 1024;
859 long dalvikAllocated = dalvikMax - dalvikFree;
860 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -0700861 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700862 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
863 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 int globalAssetCount = AssetManager.getGlobalAssetCount();
865 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
866 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
867 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
868 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700869 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800871 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 // For checkin, we print one long comma-separated list of values
Dianne Hackbornb437e092011-08-05 17:50:29 -0700874 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 // NOTE: if you change anything significant below, also consider changing
876 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700877 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 // Header
881 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
882 pw.print(Process.myPid()); pw.print(',');
883 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 // Heap info - max
886 pw.print(nativeMax); pw.print(',');
887 pw.print(dalvikMax); pw.print(',');
888 pw.print("N/A,");
889 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 // Heap info - allocated
892 pw.print(nativeAllocated); pw.print(',');
893 pw.print(dalvikAllocated); pw.print(',');
894 pw.print("N/A,");
895 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 // Heap info - free
898 pw.print(nativeFree); pw.print(',');
899 pw.print(dalvikFree); pw.print(',');
900 pw.print("N/A,");
901 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 // Heap info - proportional set size
904 pw.print(memInfo.nativePss); pw.print(',');
905 pw.print(memInfo.dalvikPss); pw.print(',');
906 pw.print(memInfo.otherPss); pw.print(',');
907 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 // Heap info - shared
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700910 pw.print(memInfo.nativeSharedDirty); pw.print(',');
911 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
912 pw.print(memInfo.otherSharedDirty); pw.print(',');
913 pw.print(memInfo.nativeSharedDirty + memInfo.dalvikSharedDirty
914 + memInfo.otherSharedDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 // Heap info - private
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700917 pw.print(memInfo.nativePrivateDirty); pw.print(',');
918 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
919 pw.print(memInfo.otherPrivateDirty); pw.print(',');
920 pw.print(memInfo.nativePrivateDirty + memInfo.dalvikPrivateDirty
921 + memInfo.otherPrivateDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 // Object counts
924 pw.print(viewInstanceCount); pw.print(',');
925 pw.print(viewRootInstanceCount); pw.print(',');
926 pw.print(appContextInstanceCount); pw.print(',');
927 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 pw.print(globalAssetCount); pw.print(',');
930 pw.print(globalAssetManagerCount); pw.print(',');
931 pw.print(binderLocalObjectCount); pw.print(',');
932 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 pw.print(binderDeathObjectCount); pw.print(',');
935 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 // SQL
938 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800939 pw.print(stats.memoryUsed / 1024); pw.print(',');
940 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -0700941 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800942 for (int i = 0; i < stats.dbStats.size(); i++) {
943 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -0700944 pw.print(','); pw.print(dbStats.dbName);
945 pw.print(','); pw.print(dbStats.pageSize);
946 pw.print(','); pw.print(dbStats.dbSize);
947 pw.print(','); pw.print(dbStats.lookaside);
948 pw.print(','); pw.print(dbStats.cache);
949 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -0800950 }
Dianne Hackbornb437e092011-08-05 17:50:29 -0700951 pw.println();
Bob Leee5408332009-09-04 18:31:17 -0700952
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700953 return memInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
Bob Leee5408332009-09-04 18:31:17 -0700955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 // otherwise, show human-readable format
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700957 printRow(pw, HEAP_COLUMN, "", "", "Shared", "Private", "Heap", "Heap", "Heap");
958 printRow(pw, HEAP_COLUMN, "", "Pss", "Dirty", "Dirty", "Size", "Alloc", "Free");
959 printRow(pw, HEAP_COLUMN, "", "------", "------", "------", "------", "------",
960 "------");
961 printRow(pw, HEAP_COLUMN, "Native", memInfo.nativePss, memInfo.nativeSharedDirty,
962 memInfo.nativePrivateDirty, nativeMax, nativeAllocated, nativeFree);
963 printRow(pw, HEAP_COLUMN, "Dalvik", memInfo.dalvikPss, memInfo.dalvikSharedDirty,
964 memInfo.dalvikPrivateDirty, dalvikMax, dalvikAllocated, dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700966 int otherPss = memInfo.otherPss;
967 int otherSharedDirty = memInfo.otherSharedDirty;
968 int otherPrivateDirty = memInfo.otherPrivateDirty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700970 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Romain Guy65b345f2011-07-27 18:51:50 -0700971 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700972 memInfo.getOtherPss(i), memInfo.getOtherSharedDirty(i),
973 memInfo.getOtherPrivateDirty(i), "", "", "");
974 otherPss -= memInfo.getOtherPss(i);
975 otherSharedDirty -= memInfo.getOtherSharedDirty(i);
976 otherPrivateDirty -= memInfo.getOtherPrivateDirty(i);
977 }
978
979 printRow(pw, HEAP_COLUMN, "Unknown", otherPss, otherSharedDirty,
980 otherPrivateDirty, "", "", "");
981 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
982 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
983 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
984 nativeFree+dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985
986 pw.println(" ");
987 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -0700988 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 viewRootInstanceCount);
990
991 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
992 "Activities:", activityInstanceCount);
993
994 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
995 "AssetManagers:", globalAssetManagerCount);
996
997 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
998 "Proxy Binders:", binderProxyObjectCount);
999 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1000
1001 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 // SQLite mem info
1004 pw.println(" ");
1005 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -07001006 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -08001007 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001008 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
1009 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001010 pw.println(" ");
1011 int N = stats.dbStats.size();
1012 if (N > 0) {
1013 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -07001014 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
1015 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001016 for (int i = 0; i < N; i++) {
1017 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001018 printRow(pw, DB_INFO_FORMAT,
1019 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1020 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1021 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1022 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001023 }
1024 }
Bob Leee5408332009-09-04 18:31:17 -07001025
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001026 // Asset details.
1027 String assetAlloc = AssetManager.getAssetAllocations();
1028 if (assetAlloc != null) {
1029 pw.println(" ");
1030 pw.println(" Asset Allocations");
1031 pw.print(assetAlloc);
1032 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001033
1034 return memInfo;
1035 }
1036
1037 @Override
1038 public void dumpGfxInfo(FileDescriptor fd, String[] args) {
1039 dumpGraphicsInfo(fd);
Romain Guy65b345f2011-07-27 18:51:50 -07001040 WindowManagerImpl.getDefault().dumpGfxInfo(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
1042
Jeff Brown6754ba22011-12-14 20:20:01 -08001043 @Override
1044 public void dumpDbInfo(FileDescriptor fd, String[] args) {
1045 PrintWriter pw = new PrintWriter(new FileOutputStream(fd));
1046 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1047 SQLiteDebug.dump(printer, args);
1048 pw.flush();
1049 }
1050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 private void printRow(PrintWriter pw, String format, Object...objs) {
1052 pw.println(String.format(format, objs));
1053 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001054
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001055 public void setCoreSettings(Bundle coreSettings) {
1056 queueOrSendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001057 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001058
1059 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1060 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1061 ucd.pkg = pkg;
1062 ucd.info = info;
1063 queueOrSendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
1064 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001065
1066 public void scheduleTrimMemory(int level) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001067 queueOrSendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001068 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 }
1071
Romain Guy65b345f2011-07-27 18:51:50 -07001072 private class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 public static final int LAUNCH_ACTIVITY = 100;
1074 public static final int PAUSE_ACTIVITY = 101;
1075 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1076 public static final int STOP_ACTIVITY_SHOW = 103;
1077 public static final int STOP_ACTIVITY_HIDE = 104;
1078 public static final int SHOW_WINDOW = 105;
1079 public static final int HIDE_WINDOW = 106;
1080 public static final int RESUME_ACTIVITY = 107;
1081 public static final int SEND_RESULT = 108;
Brian Carlstromed7e0072011-03-24 13:27:57 -07001082 public static final int DESTROY_ACTIVITY = 109;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 public static final int BIND_APPLICATION = 110;
1084 public static final int EXIT_APPLICATION = 111;
1085 public static final int NEW_INTENT = 112;
1086 public static final int RECEIVER = 113;
1087 public static final int CREATE_SERVICE = 114;
1088 public static final int SERVICE_ARGS = 115;
1089 public static final int STOP_SERVICE = 116;
1090 public static final int REQUEST_THUMBNAIL = 117;
1091 public static final int CONFIGURATION_CHANGED = 118;
1092 public static final int CLEAN_UP_CONTEXT = 119;
1093 public static final int GC_WHEN_IDLE = 120;
1094 public static final int BIND_SERVICE = 121;
1095 public static final int UNBIND_SERVICE = 122;
1096 public static final int DUMP_SERVICE = 123;
1097 public static final int LOW_MEMORY = 124;
1098 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1099 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001100 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001101 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001102 public static final int DESTROY_BACKUP_AGENT = 129;
1103 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001104 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001105 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001106 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001107 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001108 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001109 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001110 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001111 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001112 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001113 public static final int TRIM_MEMORY = 140;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001114 public static final int DUMP_PROVIDER = 141;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001116 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 switch (code) {
1118 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1119 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1120 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1121 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1122 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1123 case SHOW_WINDOW: return "SHOW_WINDOW";
1124 case HIDE_WINDOW: return "HIDE_WINDOW";
1125 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1126 case SEND_RESULT: return "SEND_RESULT";
1127 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1128 case BIND_APPLICATION: return "BIND_APPLICATION";
1129 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1130 case NEW_INTENT: return "NEW_INTENT";
1131 case RECEIVER: return "RECEIVER";
1132 case CREATE_SERVICE: return "CREATE_SERVICE";
1133 case SERVICE_ARGS: return "SERVICE_ARGS";
1134 case STOP_SERVICE: return "STOP_SERVICE";
1135 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1136 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1137 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1138 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1139 case BIND_SERVICE: return "BIND_SERVICE";
1140 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1141 case DUMP_SERVICE: return "DUMP_SERVICE";
1142 case LOW_MEMORY: return "LOW_MEMORY";
1143 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1144 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001145 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001146 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1147 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001148 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001149 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001150 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001151 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001152 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001153 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001154 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001155 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001156 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001157 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001158 case TRIM_MEMORY: return "TRIM_MEMORY";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001159 case DUMP_PROVIDER: return "DUMP_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
1161 }
1162 return "(unknown)";
1163 }
1164 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001165 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 switch (msg.what) {
1167 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001168 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169
1170 r.packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001171 r.activityInfo.applicationInfo, r.compatInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001172 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 } break;
1174 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001175 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001176 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 } break;
1178 case PAUSE_ACTIVITY:
1179 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001180 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 break;
1182 case PAUSE_ACTIVITY_FINISHING:
1183 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1184 break;
1185 case STOP_ACTIVITY_SHOW:
1186 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1187 break;
1188 case STOP_ACTIVITY_HIDE:
1189 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1190 break;
1191 case SHOW_WINDOW:
1192 handleWindowVisibility((IBinder)msg.obj, true);
1193 break;
1194 case HIDE_WINDOW:
1195 handleWindowVisibility((IBinder)msg.obj, false);
1196 break;
1197 case RESUME_ACTIVITY:
1198 handleResumeActivity((IBinder)msg.obj, true,
1199 msg.arg1 != 0);
1200 break;
1201 case SEND_RESULT:
1202 handleSendResult((ResultData)msg.obj);
1203 break;
1204 case DESTROY_ACTIVITY:
1205 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1206 msg.arg2, false);
1207 break;
1208 case BIND_APPLICATION:
1209 AppBindData data = (AppBindData)msg.obj;
1210 handleBindApplication(data);
1211 break;
1212 case EXIT_APPLICATION:
1213 if (mInitialApplication != null) {
1214 mInitialApplication.onTerminate();
1215 }
1216 Looper.myLooper().quit();
1217 break;
1218 case NEW_INTENT:
1219 handleNewIntent((NewIntentData)msg.obj);
1220 break;
1221 case RECEIVER:
1222 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001223 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 break;
1225 case CREATE_SERVICE:
1226 handleCreateService((CreateServiceData)msg.obj);
1227 break;
1228 case BIND_SERVICE:
1229 handleBindService((BindServiceData)msg.obj);
1230 break;
1231 case UNBIND_SERVICE:
1232 handleUnbindService((BindServiceData)msg.obj);
1233 break;
1234 case SERVICE_ARGS:
1235 handleServiceArgs((ServiceArgsData)msg.obj);
1236 break;
1237 case STOP_SERVICE:
1238 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001239 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 break;
1241 case REQUEST_THUMBNAIL:
1242 handleRequestThumbnail((IBinder)msg.obj);
1243 break;
1244 case CONFIGURATION_CHANGED:
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001245 handleConfigurationChanged((Configuration)msg.obj, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 break;
1247 case CLEAN_UP_CONTEXT:
1248 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1249 cci.context.performFinalCleanup(cci.who, cci.what);
1250 break;
1251 case GC_WHEN_IDLE:
1252 scheduleGcIdler();
1253 break;
1254 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001255 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 break;
1257 case LOW_MEMORY:
1258 handleLowMemory();
1259 break;
1260 case ACTIVITY_CONFIGURATION_CHANGED:
1261 handleActivityConfigurationChanged((IBinder)msg.obj);
1262 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001263 case PROFILER_CONTROL:
Romain Guy7eabe552011-07-21 14:56:34 -07001264 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001265 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001266 case CREATE_BACKUP_AGENT:
1267 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1268 break;
1269 case DESTROY_BACKUP_AGENT:
1270 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1271 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001272 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001273 Process.killProcess(Process.myPid());
1274 break;
1275 case REMOVE_PROVIDER:
1276 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001277 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001278 case ENABLE_JIT:
1279 ensureJitEnabled();
1280 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001281 case DISPATCH_PACKAGE_BROADCAST:
1282 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1283 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001284 case SCHEDULE_CRASH:
1285 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001286 case DUMP_HEAP:
1287 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1288 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001289 case DUMP_ACTIVITY:
1290 handleDumpActivity((DumpComponentInfo)msg.obj);
1291 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001292 case DUMP_PROVIDER:
1293 handleDumpProvider((DumpComponentInfo)msg.obj);
1294 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001295 case SLEEPING:
1296 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
1297 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001298 case SET_CORE_SETTINGS:
1299 handleSetCoreSettings((Bundle) msg.obj);
1300 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001301 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1302 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001303 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001304 case TRIM_MEMORY:
1305 handleTrimMemory(msg.arg1);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001306 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001308 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 }
Bob Leee5408332009-09-04 18:31:17 -07001310
Brian Carlstromed7e0072011-03-24 13:27:57 -07001311 private void maybeSnapshot() {
1312 if (mBoundApplication != null && SamplingProfilerIntegration.isEnabled()) {
Sen Hubde75702010-05-28 01:54:03 -07001313 // convert the *private* ActivityThread.PackageInfo to *public* known
1314 // android.content.pm.PackageInfo
1315 String packageName = mBoundApplication.info.mPackageName;
1316 android.content.pm.PackageInfo packageInfo = null;
1317 try {
1318 Context context = getSystemContext();
1319 if(context == null) {
1320 Log.e(TAG, "cannot get a valid context");
1321 return;
1322 }
1323 PackageManager pm = context.getPackageManager();
1324 if(pm == null) {
1325 Log.e(TAG, "cannot get a valid PackageManager");
1326 return;
1327 }
1328 packageInfo = pm.getPackageInfo(
1329 packageName, PackageManager.GET_ACTIVITIES);
1330 } catch (NameNotFoundException e) {
1331 Log.e(TAG, "cannot get package info for " + packageName, e);
1332 }
1333 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001334 }
1335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 }
1337
Romain Guy65b345f2011-07-27 18:51:50 -07001338 private class Idler implements MessageQueue.IdleHandler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001340 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001341 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001342 if (mBoundApplication != null && mProfiler.profileFd != null
1343 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001344 stopProfiling = true;
1345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 if (a != null) {
1347 mNewActivities = null;
1348 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001349 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001351 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 TAG, "Reporting idle of " + a +
1353 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001354 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 if (a.activity != null && !a.activity.mFinished) {
1356 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001357 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001358 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07001360 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
1362 }
1363 prev = a;
1364 a = a.nextIdle;
1365 prev.nextIdle = null;
1366 } while (a != null);
1367 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001368 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001369 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001370 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001371 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 return false;
1373 }
1374 }
1375
1376 final class GcIdler implements MessageQueue.IdleHandler {
1377 public final boolean queueIdle() {
1378 doGcIfNeeded();
1379 return false;
1380 }
1381 }
1382
Romain Guy65b345f2011-07-27 18:51:50 -07001383 private static class ResourcesKey {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001384 final private String mResDir;
1385 final private float mScale;
1386 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001387
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001388 ResourcesKey(String resDir, float scale) {
1389 mResDir = resDir;
1390 mScale = scale;
1391 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1392 }
Bob Leee5408332009-09-04 18:31:17 -07001393
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001394 @Override
1395 public int hashCode() {
1396 return mHash;
1397 }
1398
1399 @Override
1400 public boolean equals(Object obj) {
1401 if (!(obj instanceof ResourcesKey)) {
1402 return false;
1403 }
1404 ResourcesKey peer = (ResourcesKey) obj;
1405 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1406 }
1407 }
1408
Romain Guy65b345f2011-07-27 18:51:50 -07001409 public static ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001410 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412
Romain Guy65b345f2011-07-27 18:51:50 -07001413 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001414 ActivityThread am = currentActivityThread();
1415 return (am != null && am.mBoundApplication != null)
1416 ? am.mBoundApplication.processName : null;
1417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418
Romain Guy65b345f2011-07-27 18:51:50 -07001419 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001420 ActivityThread am = currentActivityThread();
1421 return am != null ? am.mInitialApplication : null;
1422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001424 public static IPackageManager getPackageManager() {
1425 if (sPackageManager != null) {
1426 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1427 return sPackageManager;
1428 }
1429 IBinder b = ServiceManager.getService("package");
1430 //Slog.v("PackageManager", "default service binder = " + b);
1431 sPackageManager = IPackageManager.Stub.asInterface(b);
1432 //Slog.v("PackageManager", "default service = " + sPackageManager);
1433 return sPackageManager;
1434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001436 DisplayMetrics getDisplayMetricsLocked(CompatibilityInfo ci, boolean forceUpdate) {
1437 DisplayMetrics dm = mDisplayMetrics.get(ci);
1438 if (dm != null && !forceUpdate) {
1439 return dm;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001440 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001441 if (dm == null) {
1442 dm = new DisplayMetrics();
1443 mDisplayMetrics.put(ci, dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001444 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001445 Display d = WindowManagerImpl.getDefault(ci).getDefaultDisplay();
1446 d.getMetrics(dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001447 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1448 // + metrics.heightPixels + " den=" + metrics.density
1449 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001450 return dm;
1451 }
1452
1453 static Configuration applyConfigCompat(Configuration config, CompatibilityInfo compat) {
1454 if (config == null) {
1455 return null;
1456 }
1457 if (compat != null && !compat.supportsScreen()) {
1458 config = new Configuration(config);
1459 compat.applyToConfiguration(config);
1460 }
1461 return config;
1462 }
1463
Romain Guy65b345f2011-07-27 18:51:50 -07001464 private Configuration mMainThreadConfig = new Configuration();
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001465 Configuration applyConfigCompatMainThread(Configuration config, CompatibilityInfo compat) {
1466 if (config == null) {
1467 return null;
1468 }
1469 if (compat != null && !compat.supportsScreen()) {
1470 mMainThreadConfig.setTo(config);
1471 config = mMainThreadConfig;
1472 compat.applyToConfiguration(config);
1473 }
1474 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001477 /**
1478 * Creates the top level Resources for applications with the given compatibility info.
1479 *
1480 * @param resDir the resource directory.
1481 * @param compInfo the compability info. It will use the default compatibility info when it's
1482 * null.
1483 */
1484 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1485 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1486 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001488 // Resources is app scale dependent.
1489 if (false) {
1490 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1491 + compInfo.applicationScale);
1492 }
1493 WeakReference<Resources> wr = mActiveResources.get(key);
1494 r = wr != null ? wr.get() : null;
1495 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1496 if (r != null && r.getAssets().isUpToDate()) {
1497 if (false) {
1498 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1499 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1500 }
1501 return r;
1502 }
1503 }
1504
1505 //if (r != null) {
1506 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1507 // + r + " " + resDir);
1508 //}
1509
1510 AssetManager assets = new AssetManager();
1511 if (assets.addAssetPath(resDir) == 0) {
1512 return null;
1513 }
1514
1515 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Dianne Hackborn836e2622011-10-04 18:32:39 -07001516 DisplayMetrics metrics = getDisplayMetricsLocked(null, false);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001517 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1518 if (false) {
1519 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1520 + r.getConfiguration() + " appScale="
1521 + r.getCompatibilityInfo().applicationScale);
1522 }
1523
1524 synchronized (mPackages) {
1525 WeakReference<Resources> wr = mActiveResources.get(key);
1526 Resources existing = wr != null ? wr.get() : null;
1527 if (existing != null && existing.getAssets().isUpToDate()) {
1528 // Someone else already created the resources while we were
1529 // unlocked; go ahead and use theirs.
1530 r.getAssets().close();
1531 return existing;
1532 }
1533
1534 // XXX need to remove entries when weak references go away
1535 mActiveResources.put(key, new WeakReference<Resources>(r));
1536 return r;
1537 }
1538 }
1539
1540 /**
1541 * Creates the top level resources for the given package.
1542 */
1543 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001544 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo.get());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001545 }
1546
1547 final Handler getHandler() {
1548 return mH;
1549 }
1550
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001551 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1552 int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001553 synchronized (mPackages) {
1554 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1556 ref = mPackages.get(packageName);
1557 } else {
1558 ref = mResourcePackages.get(packageName);
1559 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001560 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001561 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001562 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1563 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 if (packageInfo != null && (packageInfo.mResources == null
1565 || packageInfo.mResources.getAssets().isUpToDate())) {
1566 if (packageInfo.isSecurityViolation()
1567 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1568 throw new SecurityException(
1569 "Requesting code from " + packageName
1570 + " to be run in process "
1571 + mBoundApplication.processName
1572 + "/" + mBoundApplication.appInfo.uid);
1573 }
1574 return packageInfo;
1575 }
1576 }
1577
1578 ApplicationInfo ai = null;
1579 try {
1580 ai = getPackageManager().getApplicationInfo(packageName,
1581 PackageManager.GET_SHARED_LIBRARY_FILES);
1582 } catch (RemoteException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07001583 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585
1586 if (ai != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001587 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
1589
1590 return null;
1591 }
1592
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001593 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
1594 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1596 boolean securityViolation = includeCode && ai.uid != 0
1597 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1598 ? ai.uid != mBoundApplication.appInfo.uid : true);
1599 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1600 |Context.CONTEXT_IGNORE_SECURITY))
1601 == Context.CONTEXT_INCLUDE_CODE) {
1602 if (securityViolation) {
1603 String msg = "Requesting code from " + ai.packageName
1604 + " (with uid " + ai.uid + ")";
1605 if (mBoundApplication != null) {
1606 msg = msg + " to be run in process "
1607 + mBoundApplication.processName + " (with uid "
1608 + mBoundApplication.appInfo.uid + ")";
1609 }
1610 throw new SecurityException(msg);
1611 }
1612 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001613 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 }
1615
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001616 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
1617 CompatibilityInfo compatInfo) {
1618 return getPackageInfo(ai, compatInfo, null, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 }
1620
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001621 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
1622 synchronized (mPackages) {
1623 WeakReference<LoadedApk> ref;
1624 if (includeCode) {
1625 ref = mPackages.get(packageName);
1626 } else {
1627 ref = mResourcePackages.get(packageName);
1628 }
1629 return ref != null ? ref.get() : null;
1630 }
1631 }
1632
Romain Guy65b345f2011-07-27 18:51:50 -07001633 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1635 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001636 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 if (includeCode) {
1638 ref = mPackages.get(aInfo.packageName);
1639 } else {
1640 ref = mResourcePackages.get(aInfo.packageName);
1641 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001642 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 if (packageInfo == null || (packageInfo.mResources != null
1644 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001645 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 : "Loading resource-only package ") + aInfo.packageName
1647 + " (in " + (mBoundApplication != null
1648 ? mBoundApplication.processName : null)
1649 + ")");
1650 packageInfo =
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001651 new LoadedApk(this, aInfo, compatInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 securityViolation, includeCode &&
1653 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1654 if (includeCode) {
1655 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001656 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 } else {
1658 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001659 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 }
1662 return packageInfo;
1663 }
1664 }
1665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 ActivityThread() {
1667 }
1668
1669 public ApplicationThread getApplicationThread()
1670 {
1671 return mAppThread;
1672 }
1673
1674 public Instrumentation getInstrumentation()
1675 {
1676 return mInstrumentation;
1677 }
1678
1679 public Configuration getConfiguration() {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001680 return mResConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682
1683 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001684 return mProfiler != null && mProfiler.profileFile != null
1685 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
1687
1688 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001689 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
1691
1692 public Looper getLooper() {
1693 return mLooper;
1694 }
1695
1696 public Application getApplication() {
1697 return mInitialApplication;
1698 }
Bob Leee5408332009-09-04 18:31:17 -07001699
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001700 public String getProcessName() {
1701 return mBoundApplication.processName;
1702 }
Bob Leee5408332009-09-04 18:31:17 -07001703
Dianne Hackborn21556372010-02-04 16:34:40 -08001704 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 synchronized (this) {
1706 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001707 ContextImpl context =
1708 ContextImpl.createSystemContext(this);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001709 LoadedApk info = new LoadedApk(this, "android", context, null,
1710 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 context.init(info, null, this);
1712 context.getResources().updateConfiguration(
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001713 getConfiguration(), getDisplayMetricsLocked(
1714 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001716 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 // + ": " + context.getResources().getConfiguration());
1718 }
1719 }
1720 return mSystemContext;
1721 }
1722
Mike Cleron432b7132009-09-24 15:28:29 -07001723 public void installSystemApplicationInfo(ApplicationInfo info) {
1724 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001725 ContextImpl context = getSystemContext();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001726 context.init(new LoadedApk(this, "android", context, info,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001727 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO), null, this);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001728
1729 // give ourselves a default profiler
1730 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07001731 }
1732 }
1733
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001734 void ensureJitEnabled() {
1735 if (!mJitEnabled) {
1736 mJitEnabled = true;
1737 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1738 }
1739 }
1740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 void scheduleGcIdler() {
1742 if (!mGcIdlerScheduled) {
1743 mGcIdlerScheduled = true;
1744 Looper.myQueue().addIdleHandler(mGcIdler);
1745 }
1746 mH.removeMessages(H.GC_WHEN_IDLE);
1747 }
1748
1749 void unscheduleGcIdler() {
1750 if (mGcIdlerScheduled) {
1751 mGcIdlerScheduled = false;
1752 Looper.myQueue().removeIdleHandler(mGcIdler);
1753 }
1754 mH.removeMessages(H.GC_WHEN_IDLE);
1755 }
1756
1757 void doGcIfNeeded() {
1758 mGcIdlerScheduled = false;
1759 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001760 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 // + "m now=" + now);
1762 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001763 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 BinderInternal.forceGc("bg");
1765 }
1766 }
1767
Jeff Hamilton52d32032011-01-08 15:31:26 -06001768 public void registerOnActivityPausedListener(Activity activity,
1769 OnActivityPausedListener listener) {
1770 synchronized (mOnPauseListeners) {
1771 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1772 if (list == null) {
1773 list = new ArrayList<OnActivityPausedListener>();
1774 mOnPauseListeners.put(activity, list);
1775 }
1776 list.add(listener);
1777 }
1778 }
1779
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08001780 public void unregisterOnActivityPausedListener(Activity activity,
1781 OnActivityPausedListener listener) {
1782 synchronized (mOnPauseListeners) {
1783 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1784 if (list != null) {
1785 list.remove(listener);
1786 }
1787 }
1788 }
1789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 public final ActivityInfo resolveActivityInfo(Intent intent) {
1791 ActivityInfo aInfo = intent.resolveActivityInfo(
1792 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1793 if (aInfo == null) {
1794 // Throw an exception.
1795 Instrumentation.checkStartActivityResult(
1796 IActivityManager.START_CLASS_NOT_FOUND, intent);
1797 }
1798 return aInfo;
1799 }
Bob Leee5408332009-09-04 18:31:17 -07001800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001803 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001804 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001806 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 r.intent = intent;
1808 r.state = state;
1809 r.parent = parent;
1810 r.embeddedID = id;
1811 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001812 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 if (localLOGV) {
1814 ComponentName compname = intent.getComponent();
1815 String name;
1816 if (compname != null) {
1817 name = compname.toShortString();
1818 } else {
1819 name = "(Intent " + intent + ").getComponent() returned null";
1820 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001821 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 + ", comp=" + name
1823 + ", token=" + token);
1824 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001825 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827
1828 public final Activity getActivity(IBinder token) {
1829 return mActivities.get(token).activity;
1830 }
1831
1832 public final void sendActivityResult(
1833 IBinder token, String id, int requestCode,
1834 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001835 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001836 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1838 list.add(new ResultInfo(id, requestCode, resultCode, data));
1839 mAppThread.scheduleSendResult(token, list);
1840 }
1841
1842 // if the thread hasn't started yet, we don't have the handler, so just
1843 // save the messages until we're ready.
Romain Guy65b345f2011-07-27 18:51:50 -07001844 private void queueOrSendMessage(int what, Object obj) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 queueOrSendMessage(what, obj, 0, 0);
1846 }
1847
Romain Guy65b345f2011-07-27 18:51:50 -07001848 private void queueOrSendMessage(int what, Object obj, int arg1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 queueOrSendMessage(what, obj, arg1, 0);
1850 }
1851
Romain Guy65b345f2011-07-27 18:51:50 -07001852 private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001854 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1856 + ": " + arg1 + " / " + obj);
1857 Message msg = Message.obtain();
1858 msg.what = what;
1859 msg.obj = obj;
1860 msg.arg1 = arg1;
1861 msg.arg2 = arg2;
1862 mH.sendMessage(msg);
1863 }
1864 }
1865
Dianne Hackborn21556372010-02-04 16:34:40 -08001866 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 String what) {
1868 ContextCleanupInfo cci = new ContextCleanupInfo();
1869 cci.context = context;
1870 cci.who = who;
1871 cci.what = what;
1872 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1873 }
1874
Romain Guy65b345f2011-07-27 18:51:50 -07001875 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1877
1878 ActivityInfo aInfo = r.activityInfo;
1879 if (r.packageInfo == null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001880 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 Context.CONTEXT_INCLUDE_CODE);
1882 }
Bob Leee5408332009-09-04 18:31:17 -07001883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 ComponentName component = r.intent.getComponent();
1885 if (component == null) {
1886 component = r.intent.resolveActivity(
1887 mInitialApplication.getPackageManager());
1888 r.intent.setComponent(component);
1889 }
1890
1891 if (r.activityInfo.targetActivity != null) {
1892 component = new ComponentName(r.activityInfo.packageName,
1893 r.activityInfo.targetActivity);
1894 }
1895
1896 Activity activity = null;
1897 try {
1898 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1899 activity = mInstrumentation.newActivity(
1900 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001901 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 r.intent.setExtrasClassLoader(cl);
1903 if (r.state != null) {
1904 r.state.setClassLoader(cl);
1905 }
1906 } catch (Exception e) {
1907 if (!mInstrumentation.onException(activity, e)) {
1908 throw new RuntimeException(
1909 "Unable to instantiate activity " + component
1910 + ": " + e.toString(), e);
1911 }
1912 }
1913
1914 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001915 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001916
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001917 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1918 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 TAG, r + ": app=" + app
1920 + ", appName=" + app.getPackageName()
1921 + ", pkg=" + r.packageInfo.getPackageName()
1922 + ", comp=" + r.intent.getComponent().toShortString()
1923 + ", dir=" + r.packageInfo.getAppDir());
1924
1925 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001926 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 appContext.init(r.packageInfo, r.token, this);
1928 appContext.setOuterContext(activity);
1929 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001930 Configuration config = new Configuration(mCompatConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001931 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001932 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001933 activity.attach(appContext, this, getInstrumentation(), r.token,
1934 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001935 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001936
Christopher Tateb70f3df2009-04-07 16:07:59 -07001937 if (customIntent != null) {
1938 activity.mIntent = customIntent;
1939 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001940 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 activity.mStartedActivity = false;
1942 int theme = r.activityInfo.getThemeResource();
1943 if (theme != 0) {
1944 activity.setTheme(theme);
1945 }
1946
1947 activity.mCalled = false;
1948 mInstrumentation.callActivityOnCreate(activity, r.state);
1949 if (!activity.mCalled) {
1950 throw new SuperNotCalledException(
1951 "Activity " + r.intent.getComponent().toShortString() +
1952 " did not call through to super.onCreate()");
1953 }
1954 r.activity = activity;
1955 r.stopped = true;
1956 if (!r.activity.mFinished) {
1957 activity.performStart();
1958 r.stopped = false;
1959 }
1960 if (!r.activity.mFinished) {
1961 if (r.state != null) {
1962 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1963 }
1964 }
1965 if (!r.activity.mFinished) {
1966 activity.mCalled = false;
1967 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1968 if (!activity.mCalled) {
1969 throw new SuperNotCalledException(
1970 "Activity " + r.intent.getComponent().toShortString() +
1971 " did not call through to super.onPostCreate()");
1972 }
1973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
1975 r.paused = true;
1976
1977 mActivities.put(r.token, r);
1978
1979 } catch (SuperNotCalledException e) {
1980 throw e;
1981
1982 } catch (Exception e) {
1983 if (!mInstrumentation.onException(activity, e)) {
1984 throw new RuntimeException(
1985 "Unable to start activity " + component
1986 + ": " + e.toString(), e);
1987 }
1988 }
1989
1990 return activity;
1991 }
1992
Romain Guy65b345f2011-07-27 18:51:50 -07001993 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 // If we are getting ready to gc after going to the background, well
1995 // we are back active so skip it.
1996 unscheduleGcIdler();
1997
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001998 if (r.profileFd != null) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001999 mProfiler.setProfiler(r.profileFile, r.profileFd);
2000 mProfiler.startProfiling();
2001 mProfiler.autoStopProfiler = r.autoStopProfiler;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002002 }
2003
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002004 // Make sure we are running with the most recent config.
2005 handleConfigurationChanged(null, null);
2006
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002007 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002009 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010
2011 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002012 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002013 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 handleResumeActivity(r.token, false, r.isForward);
2015
2016 if (!r.activity.mFinished && r.startsNotResumed) {
2017 // The activity manager actually wants this one to start out
2018 // paused, because it needs to be visible but isn't in the
2019 // foreground. We accomplish this by going through the
2020 // normal startup (because activities expect to go through
2021 // onResume() the first time they run, before their window
2022 // is displayed), and then pausing it. However, in this case
2023 // we do -not- need to do the full pause cycle (of freezing
2024 // and such) because the activity manager assumes it can just
2025 // retain the current state it has.
2026 try {
2027 r.activity.mCalled = false;
2028 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002029 // We need to keep around the original state, in case
2030 // we need to be created again.
2031 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 if (!r.activity.mCalled) {
2033 throw new SuperNotCalledException(
2034 "Activity " + r.intent.getComponent().toShortString() +
2035 " did not call through to super.onPause()");
2036 }
2037
2038 } catch (SuperNotCalledException e) {
2039 throw e;
2040
2041 } catch (Exception e) {
2042 if (!mInstrumentation.onException(r.activity, e)) {
2043 throw new RuntimeException(
2044 "Unable to pause activity "
2045 + r.intent.getComponent().toShortString()
2046 + ": " + e.toString(), e);
2047 }
2048 }
2049 r.paused = true;
2050 }
2051 } else {
2052 // If there was an error, for any reason, tell the activity
2053 // manager to stop us.
2054 try {
2055 ActivityManagerNative.getDefault()
2056 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2057 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07002058 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
2060 }
2061 }
2062
Romain Guy65b345f2011-07-27 18:51:50 -07002063 private void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 List<Intent> intents) {
2065 final int N = intents.size();
2066 for (int i=0; i<N; i++) {
2067 Intent intent = intents.get(i);
2068 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002069 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2071 }
2072 }
2073
2074 public final void performNewIntents(IBinder token,
2075 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002076 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 if (r != null) {
2078 final boolean resumed = !r.paused;
2079 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002080 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 mInstrumentation.callActivityOnPause(r.activity);
2082 }
2083 deliverNewIntents(r, intents);
2084 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07002085 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002086 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 }
2088 }
2089 }
Bob Leee5408332009-09-04 18:31:17 -07002090
Romain Guy65b345f2011-07-27 18:51:50 -07002091 private void handleNewIntent(NewIntentData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 performNewIntents(data.token, data.intents);
2093 }
2094
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002095 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
2096
2097 /**
2098 * Return the Intent that's currently being handled by a
2099 * BroadcastReceiver on this thread, or null if none.
2100 * @hide
2101 */
2102 public static Intent getIntentBeingBroadcast() {
2103 return sCurrentBroadcastIntent.get();
2104 }
2105
Romain Guy65b345f2011-07-27 18:51:50 -07002106 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 // If we are getting ready to gc after going to the background, well
2108 // we are back active so skip it.
2109 unscheduleGcIdler();
2110
2111 String component = data.intent.getComponent().getClassName();
2112
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002113 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002114 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115
2116 IActivityManager mgr = ActivityManagerNative.getDefault();
2117
Romain Guy65b345f2011-07-27 18:51:50 -07002118 BroadcastReceiver receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 try {
2120 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2121 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002122 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2124 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002125 if (DEBUG_BROADCAST) Slog.i(TAG,
2126 "Finishing failed broadcast to " + data.intent.getComponent());
2127 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 throw new RuntimeException(
2129 "Unable to instantiate receiver " + component
2130 + ": " + e.toString(), e);
2131 }
2132
2133 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002134 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002135
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002136 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 TAG, "Performing receive of " + data.intent
2138 + ": app=" + app
2139 + ", appName=" + app.getPackageName()
2140 + ", pkg=" + packageInfo.getPackageName()
2141 + ", comp=" + data.intent.getComponent().toShortString()
2142 + ", dir=" + packageInfo.getAppDir());
2143
Dianne Hackborn21556372010-02-04 16:34:40 -08002144 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002145 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002146 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 receiver.onReceive(context.getReceiverRestrictedContext(),
2148 data.intent);
2149 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002150 if (DEBUG_BROADCAST) Slog.i(TAG,
2151 "Finishing failed broadcast to " + data.intent.getComponent());
2152 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 if (!mInstrumentation.onException(receiver, e)) {
2154 throw new RuntimeException(
2155 "Unable to start receiver " + component
2156 + ": " + e.toString(), e);
2157 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002158 } finally {
2159 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 }
2161
Dianne Hackborne829fef2010-10-26 17:44:01 -07002162 if (receiver.getPendingResult() != null) {
2163 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
2165 }
2166
Christopher Tate181fafa2009-05-14 11:12:14 -07002167 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07002168 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002169 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002170
2171 // no longer idle; we have backup work to do
2172 unscheduleGcIdler();
2173
2174 // instantiate the BackupAgent class named in the manifest
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002175 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002176 String packageName = packageInfo.mPackageName;
2177 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002178 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07002179 + " already exists");
2180 return;
2181 }
Bob Leee5408332009-09-04 18:31:17 -07002182
Christopher Tate181fafa2009-05-14 11:12:14 -07002183 BackupAgent agent = null;
2184 String classname = data.appInfo.backupAgentName;
Christopher Tate4a627c72011-04-01 14:43:32 -07002185
Christopher Tate79ec80d2011-06-24 14:58:49 -07002186 // full backup operation but no app-supplied agent? use the default implementation
2187 if (classname == null && (data.backupMode == IApplicationThread.BACKUP_MODE_FULL
2188 || data.backupMode == IApplicationThread.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002189 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07002190 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002191
Christopher Tate181fafa2009-05-14 11:12:14 -07002192 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002193 IBinder binder = null;
2194 try {
Christopher Tate4a627c72011-04-01 14:43:32 -07002195 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
2196
Christopher Tated1475e02009-07-09 15:36:17 -07002197 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Christopher Tate4a627c72011-04-01 14:43:32 -07002198 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tated1475e02009-07-09 15:36:17 -07002199
2200 // set up the agent's context
Dianne Hackborn21556372010-02-04 16:34:40 -08002201 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07002202 context.init(packageInfo, null, this);
2203 context.setOuterContext(agent);
2204 agent.attach(context);
2205
2206 agent.onCreate();
2207 binder = agent.onBind();
2208 mBackupAgents.put(packageName, agent);
2209 } catch (Exception e) {
2210 // If this is during restore, fail silently; otherwise go
2211 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002212 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tate75a99702011-05-18 16:28:19 -07002213 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE
2214 && data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE_FULL) {
Christopher Tated1475e02009-07-09 15:36:17 -07002215 throw e;
2216 }
2217 // falling through with 'binder' still null
2218 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002219
2220 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002221 try {
2222 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2223 } catch (RemoteException e) {
2224 // nothing to do.
2225 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002226 } catch (Exception e) {
2227 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07002228 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07002229 }
2230 }
2231
2232 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07002233 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002234 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002235
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002236 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002237 String packageName = packageInfo.mPackageName;
2238 BackupAgent agent = mBackupAgents.get(packageName);
2239 if (agent != null) {
2240 try {
2241 agent.onDestroy();
2242 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002243 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002244 e.printStackTrace();
2245 }
2246 mBackupAgents.remove(packageName);
2247 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002248 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002249 }
2250 }
2251
Romain Guy65b345f2011-07-27 18:51:50 -07002252 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 // If we are getting ready to gc after going to the background, well
2254 // we are back active so skip it.
2255 unscheduleGcIdler();
2256
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002257 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002258 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 Service service = null;
2260 try {
2261 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2262 service = (Service) cl.loadClass(data.info.name).newInstance();
2263 } catch (Exception e) {
2264 if (!mInstrumentation.onException(service, e)) {
2265 throw new RuntimeException(
2266 "Unable to instantiate service " + data.info.name
2267 + ": " + e.toString(), e);
2268 }
2269 }
2270
2271 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002272 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273
Dianne Hackborn21556372010-02-04 16:34:40 -08002274 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 context.init(packageInfo, null, this);
2276
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002277 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 context.setOuterContext(service);
2279 service.attach(context, this, data.info.name, data.token, app,
2280 ActivityManagerNative.getDefault());
2281 service.onCreate();
2282 mServices.put(data.token, service);
2283 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002284 ActivityManagerNative.getDefault().serviceDoneExecuting(
2285 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 } catch (RemoteException e) {
2287 // nothing to do.
2288 }
2289 } catch (Exception e) {
2290 if (!mInstrumentation.onException(service, e)) {
2291 throw new RuntimeException(
2292 "Unable to create service " + data.info.name
2293 + ": " + e.toString(), e);
2294 }
2295 }
2296 }
2297
Romain Guy65b345f2011-07-27 18:51:50 -07002298 private void handleBindService(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 try {
2304 if (!data.rebind) {
2305 IBinder binder = s.onBind(data.intent);
2306 ActivityManagerNative.getDefault().publishService(
2307 data.token, data.intent, binder);
2308 } else {
2309 s.onRebind(data.intent);
2310 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002311 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002313 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 } catch (RemoteException ex) {
2315 }
2316 } catch (Exception e) {
2317 if (!mInstrumentation.onException(s, e)) {
2318 throw new RuntimeException(
2319 "Unable to bind to service " + s
2320 + " with " + data.intent + ": " + e.toString(), e);
2321 }
2322 }
2323 }
2324 }
2325
Romain Guy65b345f2011-07-27 18:51:50 -07002326 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 Service s = mServices.get(data.token);
2328 if (s != null) {
2329 try {
2330 data.intent.setExtrasClassLoader(s.getClassLoader());
2331 boolean doRebind = s.onUnbind(data.intent);
2332 try {
2333 if (doRebind) {
2334 ActivityManagerNative.getDefault().unbindFinished(
2335 data.token, data.intent, doRebind);
2336 } else {
2337 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002338 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 }
2340 } catch (RemoteException ex) {
2341 }
2342 } catch (Exception e) {
2343 if (!mInstrumentation.onException(s, e)) {
2344 throw new RuntimeException(
2345 "Unable to unbind to service " + s
2346 + " with " + data.intent + ": " + e.toString(), e);
2347 }
2348 }
2349 }
2350 }
2351
Dianne Hackborn625ac272010-09-17 18:29:22 -07002352 private void handleDumpService(DumpComponentInfo info) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002353 Service s = mServices.get(info.token);
2354 if (s != null) {
2355 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2356 s.dump(info.fd.getFileDescriptor(), pw, info.args);
2357 pw.flush();
2358 try {
2359 info.fd.close();
2360 } catch (IOException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 }
2362 }
2363 }
2364
Dianne Hackborn625ac272010-09-17 18:29:22 -07002365 private void handleDumpActivity(DumpComponentInfo info) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002366 ActivityClientRecord r = mActivities.get(info.token);
2367 if (r != null && r.activity != null) {
2368 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2369 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
2370 pw.flush();
2371 try {
2372 info.fd.close();
2373 } catch (IOException e) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002374 }
2375 }
2376 }
2377
Marco Nelissen18cb2872011-11-15 11:19:53 -08002378 private void handleDumpProvider(DumpComponentInfo info) {
2379 ProviderClientRecord r = mLocalProviders.get(info.token);
2380 if (r != null && r.mLocalProvider != null) {
2381 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2382 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
2383 pw.flush();
2384 try {
2385 info.fd.close();
2386 } catch (IOException e) {
2387 }
2388 }
2389 }
2390
Romain Guy65b345f2011-07-27 18:51:50 -07002391 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 Service s = mServices.get(data.token);
2393 if (s != null) {
2394 try {
2395 if (data.args != null) {
2396 data.args.setExtrasClassLoader(s.getClassLoader());
2397 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002398 int res;
2399 if (!data.taskRemoved) {
2400 res = s.onStartCommand(data.args, data.flags, data.startId);
2401 } else {
2402 s.onTaskRemoved(data.args);
2403 res = Service.START_TASK_REMOVED_COMPLETE;
2404 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002405
2406 QueuedWork.waitToFinish();
2407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002409 ActivityManagerNative.getDefault().serviceDoneExecuting(
2410 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 } catch (RemoteException e) {
2412 // nothing to do.
2413 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002414 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 } catch (Exception e) {
2416 if (!mInstrumentation.onException(s, e)) {
2417 throw new RuntimeException(
2418 "Unable to start service " + s
2419 + " with " + data.args + ": " + e.toString(), e);
2420 }
2421 }
2422 }
2423 }
2424
Romain Guy65b345f2011-07-27 18:51:50 -07002425 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 Service s = mServices.remove(token);
2427 if (s != null) {
2428 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002429 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 s.onDestroy();
2431 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002432 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002434 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002436
2437 QueuedWork.waitToFinish();
2438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002440 ActivityManagerNative.getDefault().serviceDoneExecuting(
2441 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 } catch (RemoteException e) {
2443 // nothing to do.
2444 }
2445 } catch (Exception e) {
2446 if (!mInstrumentation.onException(s, e)) {
2447 throw new RuntimeException(
2448 "Unable to stop service " + s
2449 + ": " + e.toString(), e);
2450 }
2451 }
2452 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002453 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 }
2455
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002456 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002458 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002459 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 + " finished=" + r.activity.mFinished);
2461 if (r != null && !r.activity.mFinished) {
2462 if (clearHide) {
2463 r.hideForNow = false;
2464 r.activity.mStartedActivity = false;
2465 }
2466 try {
2467 if (r.pendingIntents != null) {
2468 deliverNewIntents(r, r.pendingIntents);
2469 r.pendingIntents = null;
2470 }
2471 if (r.pendingResults != null) {
2472 deliverResults(r, r.pendingResults);
2473 r.pendingResults = null;
2474 }
2475 r.activity.performResume();
2476
Bob Leee5408332009-09-04 18:31:17 -07002477 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 r.paused = false;
2481 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 r.state = null;
2483 } catch (Exception e) {
2484 if (!mInstrumentation.onException(r.activity, e)) {
2485 throw new RuntimeException(
2486 "Unable to resume activity "
2487 + r.intent.getComponent().toShortString()
2488 + ": " + e.toString(), e);
2489 }
2490 }
2491 }
2492 return r;
2493 }
2494
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002495 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
2496 if (r.mPendingRemoveWindow != null) {
2497 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2498 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2499 if (wtoken != null) {
2500 WindowManagerImpl.getDefault().closeAll(wtoken,
2501 r.activity.getClass().getName(), "Activity");
2502 }
2503 }
2504 r.mPendingRemoveWindow = null;
2505 r.mPendingRemoveWindowManager = null;
2506 }
2507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2509 // If we are getting ready to gc after going to the background, well
2510 // we are back active so skip it.
2511 unscheduleGcIdler();
2512
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002513 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514
2515 if (r != null) {
2516 final Activity a = r.activity;
2517
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002518 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 TAG, "Resume " + r + " started activity: " +
2520 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2521 + ", finished: " + a.mFinished);
2522
2523 final int forwardBit = isForward ?
2524 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 // If the window hasn't yet been added to the window manager,
2527 // and this guy didn't finish itself or start another activity,
2528 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002529 boolean willBeVisible = !a.mStartedActivity;
2530 if (!willBeVisible) {
2531 try {
2532 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2533 a.getActivityToken());
2534 } catch (RemoteException e) {
2535 }
2536 }
2537 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 r.window = r.activity.getWindow();
2539 View decor = r.window.getDecorView();
2540 decor.setVisibility(View.INVISIBLE);
2541 ViewManager wm = a.getWindowManager();
2542 WindowManager.LayoutParams l = r.window.getAttributes();
2543 a.mDecor = decor;
2544 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2545 l.softInputMode |= forwardBit;
2546 if (a.mVisibleFromClient) {
2547 a.mWindowAdded = true;
2548 wm.addView(decor, l);
2549 }
2550
2551 // If the window has already been added, but during resume
2552 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002553 // window visible.
2554 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002555 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 TAG, "Launch " + r + " mStartedActivity set");
2557 r.hideForNow = true;
2558 }
2559
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002560 // Get rid of anything left hanging around.
2561 cleanUpPendingRemoveWindows(r);
2562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 // The window is now visible if it has been added, we are not
2564 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002565 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002566 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002568 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002569 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 performConfigurationChanged(r.activity, r.newConfig);
2571 r.newConfig = null;
2572 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002573 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 + isForward);
2575 WindowManager.LayoutParams l = r.window.getAttributes();
2576 if ((l.softInputMode
2577 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2578 != forwardBit) {
2579 l.softInputMode = (l.softInputMode
2580 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2581 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002582 if (r.activity.mVisibleFromClient) {
2583 ViewManager wm = a.getWindowManager();
2584 View decor = r.window.getDecorView();
2585 wm.updateViewLayout(decor, l);
2586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 }
2588 r.activity.mVisibleFromServer = true;
2589 mNumVisibleActivities++;
2590 if (r.activity.mVisibleFromClient) {
2591 r.activity.makeVisible();
2592 }
2593 }
2594
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002595 if (!r.onlyLocalRequest) {
2596 r.nextIdle = mNewActivities;
2597 mNewActivities = r;
2598 if (localLOGV) Slog.v(
2599 TAG, "Scheduling idle handler for " + r);
2600 Looper.myQueue().addIdleHandler(new Idler());
2601 }
2602 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603
2604 } else {
2605 // If an exception was thrown when trying to resume, then
2606 // just end this activity.
2607 try {
2608 ActivityManagerNative.getDefault()
2609 .finishActivity(token, Activity.RESULT_CANCELED, null);
2610 } catch (RemoteException ex) {
2611 }
2612 }
2613 }
2614
2615 private int mThumbnailWidth = -1;
2616 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002617 private Bitmap mAvailThumbnailBitmap = null;
2618 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619
Romain Guy65b345f2011-07-27 18:51:50 -07002620 private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002621 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002623 if (thumbnail == null) {
2624 int w = mThumbnailWidth;
2625 int h;
2626 if (w < 0) {
2627 Resources res = r.activity.getResources();
2628 mThumbnailHeight = h =
2629 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002631 mThumbnailWidth = w =
2632 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2633 } else {
2634 h = mThumbnailHeight;
2635 }
2636
2637 // On platforms where we don't want thumbnails, set dims to (0,0)
2638 if ((w > 0) && (h > 0)) {
2639 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2640 thumbnail.eraseColor(0);
2641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
2643
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002644 if (thumbnail != null) {
2645 Canvas cv = mThumbnailCanvas;
2646 if (cv == null) {
2647 mThumbnailCanvas = cv = new Canvas();
2648 }
2649
2650 cv.setBitmap(thumbnail);
2651 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2652 mAvailThumbnailBitmap = thumbnail;
2653 thumbnail = null;
2654 }
Dianne Hackborn6311d0a2011-08-02 16:37:58 -07002655 cv.setBitmap(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 } catch (Exception e) {
2659 if (!mInstrumentation.onException(r.activity, e)) {
2660 throw new RuntimeException(
2661 "Unable to create thumbnail of "
2662 + r.intent.getComponent().toShortString()
2663 + ": " + e.toString(), e);
2664 }
2665 thumbnail = null;
2666 }
2667
2668 return thumbnail;
2669 }
2670
Romain Guy65b345f2011-07-27 18:51:50 -07002671 private void handlePauseActivity(IBinder token, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002673 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002675 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 if (userLeaving) {
2677 performUserLeavingActivity(r);
2678 }
Bob Leee5408332009-09-04 18:31:17 -07002679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002681 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002683 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002684 if (r.isPreHoneycomb()) {
2685 QueuedWork.waitToFinish();
2686 }
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 // Tell the activity manager we have paused.
2689 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002690 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 } catch (RemoteException ex) {
2692 }
2693 }
2694 }
2695
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002696 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 mInstrumentation.callActivityOnUserLeaving(r.activity);
2698 }
2699
2700 final Bundle performPauseActivity(IBinder token, boolean finished,
2701 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002702 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 return r != null ? performPauseActivity(r, finished, saveState) : null;
2704 }
2705
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002706 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 boolean saveState) {
2708 if (r.paused) {
2709 if (r.activity.mFinished) {
2710 // If we are finishing, we won't call onResume() in certain cases.
2711 // So here we likewise don't want to call onPause() if the activity
2712 // isn't resumed.
2713 return null;
2714 }
2715 RuntimeException e = new RuntimeException(
2716 "Performing pause of activity that is not resumed: "
2717 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002718 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 }
2720 Bundle state = null;
2721 if (finished) {
2722 r.activity.mFinished = true;
2723 }
2724 try {
2725 // Next have the activity save its current state and managed dialogs...
2726 if (!r.activity.mFinished && saveState) {
2727 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002728 state.setAllowFds(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2730 r.state = state;
2731 }
2732 // Now we are idle.
2733 r.activity.mCalled = false;
2734 mInstrumentation.callActivityOnPause(r.activity);
2735 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2736 if (!r.activity.mCalled) {
2737 throw new SuperNotCalledException(
2738 "Activity " + r.intent.getComponent().toShortString() +
2739 " did not call through to super.onPause()");
2740 }
2741
2742 } catch (SuperNotCalledException e) {
2743 throw e;
2744
2745 } catch (Exception e) {
2746 if (!mInstrumentation.onException(r.activity, e)) {
2747 throw new RuntimeException(
2748 "Unable to pause activity "
2749 + r.intent.getComponent().toShortString()
2750 + ": " + e.toString(), e);
2751 }
2752 }
2753 r.paused = true;
Jeff Hamilton52d32032011-01-08 15:31:26 -06002754
2755 // Notify any outstanding on paused listeners
2756 ArrayList<OnActivityPausedListener> listeners;
2757 synchronized (mOnPauseListeners) {
2758 listeners = mOnPauseListeners.remove(r.activity);
2759 }
2760 int size = (listeners != null ? listeners.size() : 0);
2761 for (int i = 0; i < size; i++) {
2762 listeners.get(i).onPaused(r.activity);
2763 }
2764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 return state;
2766 }
2767
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002768 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002769 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002770 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 }
2772
2773 private static class StopInfo {
2774 Bitmap thumbnail;
2775 CharSequence description;
2776 }
2777
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002778 private static final class ProviderRefCount {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 public int count;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 ProviderRefCount(int pCount) {
2782 count = pCount;
2783 }
2784 }
2785
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002786 /**
2787 * Core implementation of stopping an activity. Note this is a little
2788 * tricky because the server's meaning of stop is slightly different
2789 * than our client -- for the server, stop means to save state and give
2790 * it the result when it is done, but the window may still be visible.
2791 * For the client, we want to call onStop()/onStart() to indicate when
2792 * the activity's UI visibillity changes.
2793 */
Romain Guy65b345f2011-07-27 18:51:50 -07002794 private void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002795 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002796 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002797 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 if (r != null) {
2799 if (!keepShown && r.stopped) {
2800 if (r.activity.mFinished) {
2801 // If we are finishing, we won't call onResume() in certain
2802 // cases. So here we likewise don't want to call onStop()
2803 // if the activity isn't resumed.
2804 return;
2805 }
2806 RuntimeException e = new RuntimeException(
2807 "Performing stop of activity that is not resumed: "
2808 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002809 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 }
2811
2812 if (info != null) {
2813 try {
2814 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07002815 // For now, don't create the thumbnail here; we are
2816 // doing that by doing a screen snapshot.
2817 info.thumbnail = null; //createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 info.description = r.activity.onCreateDescription();
2819 } catch (Exception e) {
2820 if (!mInstrumentation.onException(r.activity, e)) {
2821 throw new RuntimeException(
2822 "Unable to save state of activity "
2823 + r.intent.getComponent().toShortString()
2824 + ": " + e.toString(), e);
2825 }
2826 }
2827 }
2828
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002829 // Next have the activity save its current state and managed dialogs...
2830 if (!r.activity.mFinished && saveState) {
2831 if (r.state == null) {
2832 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002833 state.setAllowFds(false);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002834 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2835 r.state = state;
2836 } else {
2837 state = r.state;
2838 }
2839 }
2840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 if (!keepShown) {
2842 try {
2843 // Now we are idle.
2844 r.activity.performStop();
2845 } catch (Exception e) {
2846 if (!mInstrumentation.onException(r.activity, e)) {
2847 throw new RuntimeException(
2848 "Unable to stop activity "
2849 + r.intent.getComponent().toShortString()
2850 + ": " + e.toString(), e);
2851 }
2852 }
2853 r.stopped = true;
2854 }
2855
2856 r.paused = true;
2857 }
2858 }
2859
Romain Guy65b345f2011-07-27 18:51:50 -07002860 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 View v = r.activity.mDecor;
2862 if (v != null) {
2863 if (show) {
2864 if (!r.activity.mVisibleFromServer) {
2865 r.activity.mVisibleFromServer = true;
2866 mNumVisibleActivities++;
2867 if (r.activity.mVisibleFromClient) {
2868 r.activity.makeVisible();
2869 }
2870 }
2871 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002872 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002873 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 performConfigurationChanged(r.activity, r.newConfig);
2875 r.newConfig = null;
2876 }
2877 } else {
2878 if (r.activity.mVisibleFromServer) {
2879 r.activity.mVisibleFromServer = false;
2880 mNumVisibleActivities--;
2881 v.setVisibility(View.INVISIBLE);
2882 }
2883 }
2884 }
2885 }
2886
Romain Guy65b345f2011-07-27 18:51:50 -07002887 private void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002888 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 r.activity.mConfigChangeFlags |= configChanges;
2890
2891 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002892 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002894 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 TAG, "Finishing stop of " + r + ": show=" + show
2896 + " win=" + r.window);
2897
2898 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002899
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002900 // Make sure any pending writes are now committed.
2901 if (!r.isPreHoneycomb()) {
2902 QueuedWork.waitToFinish();
2903 }
2904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 // Tell activity manager we have been stopped.
2906 try {
2907 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002908 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 } catch (RemoteException ex) {
2910 }
2911 }
2912
2913 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002914 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 if (r.stopped) {
2916 r.activity.performRestart();
2917 r.stopped = false;
2918 }
2919 }
2920
Romain Guy65b345f2011-07-27 18:51:50 -07002921 private void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002922 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002923
2924 if (r == null) {
2925 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2926 return;
2927 }
2928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002930 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 } else if (show && r.stopped) {
2932 // If we are getting ready to gc after going to the background, well
2933 // we are back active so skip it.
2934 unscheduleGcIdler();
2935
2936 r.activity.performRestart();
2937 r.stopped = false;
2938 }
2939 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07002940 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 TAG, "Handle window " + r + " visibility: " + show);
2942 updateVisibility(r, show);
2943 }
2944 }
2945
Romain Guy65b345f2011-07-27 18:51:50 -07002946 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002947 ActivityClientRecord r = mActivities.get(token);
2948
2949 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002950 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002951 return;
2952 }
2953
2954 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002955 if (!r.stopped && !r.isPreHoneycomb()) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002956 try {
2957 // Now we are idle.
2958 r.activity.performStop();
2959 } catch (Exception e) {
2960 if (!mInstrumentation.onException(r.activity, e)) {
2961 throw new RuntimeException(
2962 "Unable to stop activity "
2963 + r.intent.getComponent().toShortString()
2964 + ": " + e.toString(), e);
2965 }
2966 }
2967 r.stopped = true;
2968 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002969
2970 // Make sure any pending writes are now committed.
2971 if (!r.isPreHoneycomb()) {
2972 QueuedWork.waitToFinish();
2973 }
2974
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002975 // Tell activity manager we slept.
2976 try {
2977 ActivityManagerNative.getDefault().activitySlept(r.token);
2978 } catch (RemoteException ex) {
2979 }
2980 } else {
2981 if (r.stopped && r.activity.mVisibleFromServer) {
2982 r.activity.performRestart();
2983 r.stopped = false;
2984 }
2985 }
2986 }
2987
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002988 private void handleSetCoreSettings(Bundle coreSettings) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08002989 synchronized (mPackages) {
2990 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002991 }
2992 }
2993
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002994 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
2995 LoadedApk apk = peekPackageInfo(data.pkg, false);
2996 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002997 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002998 }
2999 apk = peekPackageInfo(data.pkg, true);
3000 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003001 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003002 }
3003 handleConfigurationChanged(mConfiguration, data.info);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003004 WindowManagerImpl.getDefault().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003005 }
3006
Romain Guy65b345f2011-07-27 18:51:50 -07003007 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 final int N = results.size();
3009 for (int i=0; i<N; i++) {
3010 ResultInfo ri = results.get(i);
3011 try {
3012 if (ri.mData != null) {
3013 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3014 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003015 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07003016 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 r.activity.dispatchActivityResult(ri.mResultWho,
3018 ri.mRequestCode, ri.mResultCode, ri.mData);
3019 } catch (Exception e) {
3020 if (!mInstrumentation.onException(r.activity, e)) {
3021 throw new RuntimeException(
3022 "Failure delivering result " + ri + " to activity "
3023 + r.intent.getComponent().toShortString()
3024 + ": " + e.toString(), e);
3025 }
3026 }
3027 }
3028 }
3029
Romain Guy65b345f2011-07-27 18:51:50 -07003030 private void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003031 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003032 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 if (r != null) {
3034 final boolean resumed = !r.paused;
3035 if (!r.activity.mFinished && r.activity.mDecor != null
3036 && r.hideForNow && resumed) {
3037 // We had hidden the activity because it started another
3038 // one... we have gotten a result back and we are not
3039 // paused, so make sure our window is visible.
3040 updateVisibility(r, true);
3041 }
3042 if (resumed) {
3043 try {
3044 // Now we are idle.
3045 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003046 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 mInstrumentation.callActivityOnPause(r.activity);
3048 if (!r.activity.mCalled) {
3049 throw new SuperNotCalledException(
3050 "Activity " + r.intent.getComponent().toShortString()
3051 + " did not call through to super.onPause()");
3052 }
3053 } catch (SuperNotCalledException e) {
3054 throw e;
3055 } catch (Exception e) {
3056 if (!mInstrumentation.onException(r.activity, e)) {
3057 throw new RuntimeException(
3058 "Unable to pause activity "
3059 + r.intent.getComponent().toShortString()
3060 + ": " + e.toString(), e);
3061 }
3062 }
3063 }
3064 deliverResults(r, res.results);
3065 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07003066 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003067 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 }
3069 }
3070 }
3071
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003072 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 return performDestroyActivity(token, finishing, 0, false);
3074 }
3075
Romain Guy65b345f2011-07-27 18:51:50 -07003076 private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003078 ActivityClientRecord r = mActivities.get(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003079 Class activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003080 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003082 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 r.activity.mConfigChangeFlags |= configChanges;
3084 if (finishing) {
3085 r.activity.mFinished = true;
3086 }
3087 if (!r.paused) {
3088 try {
3089 r.activity.mCalled = false;
3090 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003091 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 r.activity.getComponentName().getClassName());
3093 if (!r.activity.mCalled) {
3094 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003095 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 + " did not call through to super.onPause()");
3097 }
3098 } catch (SuperNotCalledException e) {
3099 throw e;
3100 } catch (Exception e) {
3101 if (!mInstrumentation.onException(r.activity, e)) {
3102 throw new RuntimeException(
3103 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003104 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 + ": " + e.toString(), e);
3106 }
3107 }
3108 r.paused = true;
3109 }
3110 if (!r.stopped) {
3111 try {
3112 r.activity.performStop();
3113 } catch (SuperNotCalledException e) {
3114 throw e;
3115 } catch (Exception e) {
3116 if (!mInstrumentation.onException(r.activity, e)) {
3117 throw new RuntimeException(
3118 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003119 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 + ": " + e.toString(), e);
3121 }
3122 }
3123 r.stopped = true;
3124 }
3125 if (getNonConfigInstance) {
3126 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003127 r.lastNonConfigurationInstances
3128 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 } catch (Exception e) {
3130 if (!mInstrumentation.onException(r.activity, e)) {
3131 throw new RuntimeException(
3132 "Unable to retain activity "
3133 + r.intent.getComponent().toShortString()
3134 + ": " + e.toString(), e);
3135 }
3136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 }
3138 try {
3139 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07003140 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 if (!r.activity.mCalled) {
3142 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003143 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 " did not call through to super.onDestroy()");
3145 }
3146 if (r.window != null) {
3147 r.window.closeAllPanels();
3148 }
3149 } catch (SuperNotCalledException e) {
3150 throw e;
3151 } catch (Exception e) {
3152 if (!mInstrumentation.onException(r.activity, e)) {
3153 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003154 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3155 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 }
3157 }
3158 }
3159 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003160 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 return r;
3162 }
3163
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003164 private static String safeToComponentShortString(Intent intent) {
3165 ComponentName component = intent.getComponent();
3166 return component == null ? "[Unknown]" : component.toShortString();
3167 }
3168
Romain Guy65b345f2011-07-27 18:51:50 -07003169 private void handleDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003171 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 configChanges, getNonConfigInstance);
3173 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003174 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 WindowManager wm = r.activity.getWindowManager();
3176 View v = r.activity.mDecor;
3177 if (v != null) {
3178 if (r.activity.mVisibleFromServer) {
3179 mNumVisibleActivities--;
3180 }
3181 IBinder wtoken = v.getWindowToken();
3182 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003183 if (r.onlyLocalRequest) {
3184 // Hold off on removing this until the new activity's
3185 // window is being added.
3186 r.mPendingRemoveWindow = v;
3187 r.mPendingRemoveWindowManager = wm;
3188 } else {
3189 wm.removeViewImmediate(v);
3190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003192 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 WindowManagerImpl.getDefault().closeAll(wtoken,
3194 r.activity.getClass().getName(), "Activity");
3195 }
3196 r.activity.mDecor = null;
3197 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003198 if (r.mPendingRemoveWindow == null) {
3199 // If we are delaying the removal of the activity window, then
3200 // we can't clean up all windows here. Note that we can't do
3201 // so later either, which means any windows that aren't closed
3202 // by the app will leak. Well we try to warning them a lot
3203 // about leaking windows, because that is a bug, so if they are
3204 // using this recreate facility then they get to live with leaks.
3205 WindowManagerImpl.getDefault().closeAll(token,
3206 r.activity.getClass().getName(), "Activity");
3207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208
3209 // Mocked out contexts won't be participating in the normal
3210 // process lifecycle, but if we're running with a proper
3211 // ApplicationContext we need to have it tear down things
3212 // cleanly.
3213 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003214 if (c instanceof ContextImpl) {
3215 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 r.activity.getClass().getName(), "Activity");
3217 }
3218 }
3219 if (finishing) {
3220 try {
3221 ActivityManagerNative.getDefault().activityDestroyed(token);
3222 } catch (RemoteException ex) {
3223 // If the system process has died, it's game over for everyone.
3224 }
3225 }
3226 }
3227
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003228 public final void requestRelaunchActivity(IBinder token,
3229 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
3230 int configChanges, boolean notResumed, Configuration config,
3231 boolean fromServer) {
3232 ActivityClientRecord target = null;
3233
3234 synchronized (mPackages) {
3235 for (int i=0; i<mRelaunchingActivities.size(); i++) {
3236 ActivityClientRecord r = mRelaunchingActivities.get(i);
3237 if (r.token == token) {
3238 target = r;
3239 if (pendingResults != null) {
3240 if (r.pendingResults != null) {
3241 r.pendingResults.addAll(pendingResults);
3242 } else {
3243 r.pendingResults = pendingResults;
3244 }
3245 }
3246 if (pendingNewIntents != null) {
3247 if (r.pendingIntents != null) {
3248 r.pendingIntents.addAll(pendingNewIntents);
3249 } else {
3250 r.pendingIntents = pendingNewIntents;
3251 }
3252 }
3253 break;
3254 }
3255 }
3256
3257 if (target == null) {
3258 target = new ActivityClientRecord();
3259 target.token = token;
3260 target.pendingResults = pendingResults;
3261 target.pendingIntents = pendingNewIntents;
3262 if (!fromServer) {
3263 ActivityClientRecord existing = mActivities.get(token);
3264 if (existing != null) {
3265 target.startsNotResumed = existing.paused;
3266 }
3267 target.onlyLocalRequest = true;
3268 }
3269 mRelaunchingActivities.add(target);
3270 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
3271 }
3272
3273 if (fromServer) {
3274 target.startsNotResumed = notResumed;
3275 target.onlyLocalRequest = false;
3276 }
3277 if (config != null) {
3278 target.createdConfig = config;
3279 }
3280 target.pendingConfigChanges |= configChanges;
3281 }
3282 }
3283
Romain Guy65b345f2011-07-27 18:51:50 -07003284 private void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 // If we are getting ready to gc after going to the background, well
3286 // we are back active so skip it.
3287 unscheduleGcIdler();
3288
3289 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003290 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07003291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 // First: make sure we have the most recent configuration and most
3293 // recent version of the activity, or skip it if some previous call
3294 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003295 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 int N = mRelaunchingActivities.size();
3297 IBinder token = tmp.token;
3298 tmp = null;
3299 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003300 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 if (r.token == token) {
3302 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003303 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 mRelaunchingActivities.remove(i);
3305 i--;
3306 N--;
3307 }
3308 }
Bob Leee5408332009-09-04 18:31:17 -07003309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003311 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 return;
3313 }
Bob Leee5408332009-09-04 18:31:17 -07003314
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003315 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
3316 + tmp.token + " with configChanges=0x"
3317 + Integer.toHexString(configChanges));
3318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 if (mPendingConfiguration != null) {
3320 changedConfig = mPendingConfiguration;
3321 mPendingConfiguration = null;
3322 }
3323 }
Bob Leee5408332009-09-04 18:31:17 -07003324
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003325 if (tmp.createdConfig != null) {
3326 // If the activity manager is passing us its current config,
3327 // assume that is really what we want regardless of what we
3328 // may have pending.
3329 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003330 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
3331 && mConfiguration.diff(tmp.createdConfig) != 0)) {
3332 if (changedConfig == null
3333 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
3334 changedConfig = tmp.createdConfig;
3335 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003336 }
3337 }
3338
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003339 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003340 + tmp.token + ": changedConfig=" + changedConfig);
3341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 // If there was a pending configuration change, execute it first.
3343 if (changedConfig != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003344 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 }
Bob Leee5408332009-09-04 18:31:17 -07003346
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003347 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003348 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 if (r == null) {
3350 return;
3351 }
Bob Leee5408332009-09-04 18:31:17 -07003352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003354 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003355 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003356
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003357 r.activity.mChangingConfigurations = true;
3358
Dianne Hackborne2b04802010-12-09 09:24:55 -08003359 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08003361 performPauseActivity(r.token, false, r.isPreHoneycomb());
3362 }
3363 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
3364 r.state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04003365 r.state.setAllowFds(false);
Dianne Hackborne2b04802010-12-09 09:24:55 -08003366 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 }
Bob Leee5408332009-09-04 18:31:17 -07003368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 r.activity = null;
3372 r.window = null;
3373 r.hideForNow = false;
3374 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003375 // Merge any pending results and pending intents; don't just replace them
3376 if (tmp.pendingResults != null) {
3377 if (r.pendingResults == null) {
3378 r.pendingResults = tmp.pendingResults;
3379 } else {
3380 r.pendingResults.addAll(tmp.pendingResults);
3381 }
3382 }
3383 if (tmp.pendingIntents != null) {
3384 if (r.pendingIntents == null) {
3385 r.pendingIntents = tmp.pendingIntents;
3386 } else {
3387 r.pendingIntents.addAll(tmp.pendingIntents);
3388 }
3389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07003391
Christopher Tateb70f3df2009-04-07 16:07:59 -07003392 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 }
3394
Romain Guy65b345f2011-07-27 18:51:50 -07003395 private void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003396 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 Bitmap thumbnail = createThumbnailBitmap(r);
3398 CharSequence description = null;
3399 try {
3400 description = r.activity.onCreateDescription();
3401 } catch (Exception e) {
3402 if (!mInstrumentation.onException(r.activity, e)) {
3403 throw new RuntimeException(
3404 "Unable to create description of activity "
3405 + r.intent.getComponent().toShortString()
3406 + ": " + e.toString(), e);
3407 }
3408 }
3409 //System.out.println("Reporting top thumbnail " + thumbnail);
3410 try {
3411 ActivityManagerNative.getDefault().reportThumbnail(
3412 token, thumbnail, description);
3413 } catch (RemoteException ex) {
3414 }
3415 }
3416
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003417 ArrayList<ComponentCallbacks2> collectComponentCallbacksLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003419 ArrayList<ComponentCallbacks2> callbacks
3420 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07003421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003423 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003425 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 Activity a = ar.activity;
3427 if (a != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003428 Configuration thisConfig = applyConfigCompatMainThread(newConfig,
3429 ar.packageInfo.mCompatibilityInfo.getIfNeeded());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 if (!ar.activity.mFinished && (allActivities ||
3431 (a != null && !ar.paused))) {
3432 // If the activity is currently resumed, its configuration
3433 // needs to change right now.
3434 callbacks.add(a);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003435 } else if (thisConfig != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 // Otherwise, we will tell it about the change
3437 // the next time it is resumed or shown. Note that
3438 // the activity manager may, before then, decide the
3439 // activity needs to be destroyed to handle its new
3440 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003441 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003442 + ar.activityInfo.name + " newConfig=" + thisConfig);
3443 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 }
3445 }
3446 }
3447 }
3448 if (mServices.size() > 0) {
3449 Iterator<Service> it = mServices.values().iterator();
3450 while (it.hasNext()) {
3451 callbacks.add(it.next());
3452 }
3453 }
3454 synchronized (mProviderMap) {
3455 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003456 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 while (it.hasNext()) {
3458 callbacks.add(it.next().mLocalProvider);
3459 }
3460 }
3461 }
3462 final int N = mAllApplications.size();
3463 for (int i=0; i<N; i++) {
3464 callbacks.add(mAllApplications.get(i));
3465 }
Bob Leee5408332009-09-04 18:31:17 -07003466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 return callbacks;
3468 }
Bob Leee5408332009-09-04 18:31:17 -07003469
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003470 private final void performConfigurationChanged(
3471 ComponentCallbacks2 cb, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 // Only for Activity objects, check that they actually call up to their
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003473 // superclass implementation. ComponentCallbacks2 is an interface, so
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 // we check the runtime type and act accordingly.
3475 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3476 if (activity != null) {
3477 activity.mCalled = false;
3478 }
Bob Leee5408332009-09-04 18:31:17 -07003479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 boolean shouldChangeConfig = false;
3481 if ((activity == null) || (activity.mCurrentConfig == null)) {
3482 shouldChangeConfig = true;
3483 } else {
Bob Leee5408332009-09-04 18:31:17 -07003484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 // If the new config is the same as the config this Activity
3486 // is already running with then don't bother calling
3487 // onConfigurationChanged
3488 int diff = activity.mCurrentConfig.diff(config);
3489 if (diff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 // If this activity doesn't handle any of the config changes
3491 // then don't bother calling onConfigurationChanged as we're
3492 // going to destroy it.
Dianne Hackborne6676352011-06-01 16:51:20 -07003493 if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 shouldChangeConfig = true;
3495 }
3496 }
3497 }
Bob Leee5408332009-09-04 18:31:17 -07003498
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003499 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003500 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 if (shouldChangeConfig) {
3502 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 if (activity != null) {
3505 if (!activity.mCalled) {
3506 throw new SuperNotCalledException(
3507 "Activity " + activity.getLocalClassName() +
3508 " did not call through to super.onConfigurationChanged()");
3509 }
3510 activity.mConfigChangeFlags = 0;
3511 activity.mCurrentConfig = new Configuration(config);
3512 }
3513 }
3514 }
3515
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003516 public final void applyConfigurationToResources(Configuration config) {
3517 synchronized (mPackages) {
3518 applyConfigurationToResourcesLocked(config, null);
3519 }
3520 }
3521
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003522 final boolean applyConfigurationToResourcesLocked(Configuration config,
3523 CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003524 if (mResConfiguration == null) {
3525 mResConfiguration = new Configuration();
3526 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003527 if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003528 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003529 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003530 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003531 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003532 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003533 DisplayMetrics dm = getDisplayMetricsLocked(null, true);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003534
3535 if (compat != null && (mResCompatibilityInfo == null ||
3536 !mResCompatibilityInfo.equals(compat))) {
3537 mResCompatibilityInfo = compat;
3538 changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT
3539 | ActivityInfo.CONFIG_SCREEN_SIZE
3540 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3541 }
Bob Leee5408332009-09-04 18:31:17 -07003542
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003543 // set it for java, this also affects newly created Resources
3544 if (config.locale != null) {
3545 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 }
Bob Leee5408332009-09-04 18:31:17 -07003547
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003548 Resources.updateSystemConfiguration(config, dm, compat);
Bob Leee5408332009-09-04 18:31:17 -07003549
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003550 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003551 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003552
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003553 Iterator<WeakReference<Resources>> it =
3554 mActiveResources.values().iterator();
3555 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3556 // mActiveResources.entrySet().iterator();
3557 while (it.hasNext()) {
3558 WeakReference<Resources> v = it.next();
3559 Resources r = v.get();
3560 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003561 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003562 + r + " config to: " + config);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003563 r.updateConfiguration(config, dm, compat);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003564 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003565 // + " " + r + ": " + r.getConfiguration());
3566 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003567 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003568 it.remove();
3569 }
3570 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003571
3572 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003573 }
Dianne Hackborn836e2622011-10-04 18:32:39 -07003574
3575 final Configuration applyCompatConfiguration() {
3576 Configuration config = mConfiguration;
3577 if (mCompatConfiguration == null) {
3578 mCompatConfiguration = new Configuration();
3579 }
3580 mCompatConfiguration.setTo(mConfiguration);
3581 if (mResCompatibilityInfo != null && !mResCompatibilityInfo.supportsScreen()) {
3582 mResCompatibilityInfo.applyToConfiguration(mCompatConfiguration);
3583 config = mCompatConfiguration;
3584 }
3585 return config;
3586 }
3587
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003588 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003589
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003590 ArrayList<ComponentCallbacks2> callbacks = null;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003591
3592 synchronized (mPackages) {
3593 if (mPendingConfiguration != null) {
3594 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3595 config = mPendingConfiguration;
3596 }
3597 mPendingConfiguration = null;
3598 }
3599
3600 if (config == null) {
3601 return;
3602 }
3603
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003604 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003605 + config);
3606
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003607 applyConfigurationToResourcesLocked(config, compat);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 if (mConfiguration == null) {
3610 mConfiguration = new Configuration();
3611 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003612 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003613 return;
3614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 mConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003616 config = applyCompatConfiguration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 callbacks = collectComponentCallbacksLocked(false, config);
3618 }
Romain Guy65b345f2011-07-27 18:51:50 -07003619
3620 // Cleanup hardware accelerated stuff
3621 WindowManagerImpl.getDefault().trimLocalMemory();
Bob Leee5408332009-09-04 18:31:17 -07003622
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003623 if (callbacks != null) {
3624 final int N = callbacks.size();
3625 for (int i=0; i<N; i++) {
3626 performConfigurationChanged(callbacks.get(i), config);
3627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 }
3629 }
3630
3631 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003632 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 if (r == null || r.activity == null) {
3634 return;
3635 }
Bob Leee5408332009-09-04 18:31:17 -07003636
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003637 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003638 + r.activityInfo.name);
3639
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003640 performConfigurationChanged(r.activity, mCompatConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
3642
Romain Guy7eabe552011-07-21 14:56:34 -07003643 final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003644 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003645 try {
Romain Guy7eabe552011-07-21 14:56:34 -07003646 switch (profileType) {
3647 case 1:
3648 ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor());
3649 break;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003650 default:
3651 mProfiler.setProfiler(pcd.path, pcd.fd);
3652 mProfiler.autoStopProfiler = false;
3653 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003654 break;
3655 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003656 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003657 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003658 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003659 } finally {
3660 try {
3661 pcd.fd.close();
3662 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003663 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003664 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003665 }
3666 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07003667 switch (profileType) {
3668 case 1:
3669 ViewDebug.stopLooperProfiling();
3670 break;
3671 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003672 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003673 break;
Romain Guy7eabe552011-07-21 14:56:34 -07003674 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003675 }
3676 }
Bob Leee5408332009-09-04 18:31:17 -07003677
Andy McFadden824c5102010-07-09 16:26:57 -07003678 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3679 if (managed) {
3680 try {
3681 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3682 } catch (IOException e) {
3683 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3684 + " -- can the process access this path?");
3685 } finally {
3686 try {
3687 dhd.fd.close();
3688 } catch (IOException e) {
3689 Slog.w(TAG, "Failure closing profile fd", e);
3690 }
3691 }
3692 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003693 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003694 }
3695 }
3696
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003697 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3698 boolean hasPkgInfo = false;
3699 if (packages != null) {
3700 for (int i=packages.length-1; i>=0; i--) {
3701 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3702 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003703 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003704 ref = mPackages.get(packages[i]);
3705 if (ref != null && ref.get() != null) {
3706 hasPkgInfo = true;
3707 } else {
3708 ref = mResourcePackages.get(packages[i]);
3709 if (ref != null && ref.get() != null) {
3710 hasPkgInfo = true;
3711 }
3712 }
3713 }
3714 mPackages.remove(packages[i]);
3715 mResourcePackages.remove(packages[i]);
3716 }
3717 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003718 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003719 hasPkgInfo);
3720 }
3721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 final void handleLowMemory() {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003723 ArrayList<ComponentCallbacks2> callbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003725 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 callbacks = collectComponentCallbacksLocked(true, null);
3727 }
Bob Leee5408332009-09-04 18:31:17 -07003728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 final int N = callbacks.size();
3730 for (int i=0; i<N; i++) {
3731 callbacks.get(i).onLowMemory();
3732 }
3733
Chris Tatece229052009-03-25 16:44:52 -07003734 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3735 if (Process.myUid() != Process.SYSTEM_UID) {
3736 int sqliteReleased = SQLiteDatabase.releaseMemory();
3737 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3738 }
Bob Leee5408332009-09-04 18:31:17 -07003739
Mike Reedcaf0df12009-04-27 14:32:05 -04003740 // Ask graphics to free up as much as possible (font/image caches)
3741 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742
3743 BinderInternal.forceGc("mem");
3744 }
3745
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003746 final void handleTrimMemory(int level) {
Romain Guybdf76092011-07-18 15:00:43 -07003747 WindowManagerImpl.getDefault().trimMemory(level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003748 ArrayList<ComponentCallbacks2> callbacks;
3749
3750 synchronized (mPackages) {
3751 callbacks = collectComponentCallbacksLocked(true, null);
3752 }
3753
3754 final int N = callbacks.size();
3755 for (int i=0; i<N; i++) {
3756 callbacks.get(i).onTrimMemory(level);
3757 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003758 }
3759
Romain Guya9582652011-11-10 14:20:10 -08003760 private void setupGraphicsSupport(LoadedApk info) {
3761 try {
3762 int uid = Process.myUid();
3763 String[] packages = getPackageManager().getPackagesForUid(uid);
3764
3765 // If there are several packages in this application we won't
3766 // initialize the graphics disk caches
3767 if (packages.length == 1) {
3768 ContextImpl appContext = new ContextImpl();
3769 appContext.init(info, null, this);
3770
3771 HardwareRenderer.setupDiskCache(appContext.getCacheDir());
3772 }
3773 } catch (RemoteException e) {
3774 // Ignore
3775 }
3776 }
3777
Romain Guy65b345f2011-07-27 18:51:50 -07003778 private void handleBindApplication(AppBindData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 mBoundApplication = data;
3780 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003781 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003783 mProfiler = new Profiler();
3784 mProfiler.profileFile = data.initProfileFile;
3785 mProfiler.profileFd = data.initProfileFd;
3786 mProfiler.autoStopProfiler = data.initAutoStopProfiler;
3787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003789 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 android.ddm.DdmHandleAppName.setAppName(data.processName);
3791
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003792 if (data.persistent) {
3793 // Persistent processes on low-memory devices do not get to
3794 // use hardware accelerated drawing, since this can add too much
3795 // overhead to the process.
3796 Display display = WindowManagerImpl.getDefault().getDefaultDisplay();
3797 if (!ActivityManager.isHighEndGfx(display)) {
3798 HardwareRenderer.disable(false);
3799 }
3800 }
Romain Guya9582652011-11-10 14:20:10 -08003801
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003802 if (mProfiler.profileFd != null) {
3803 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003804 }
3805
Joe Onoratod630f102011-03-17 18:42:26 -07003806 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
3807 // implementation to use the pool executor. Normally, we use the
3808 // serialized executor as the default. This has to happen in the
3809 // main thread so the main looper is set right.
3810 if (data.appInfo.targetSdkVersion <= 12) {
3811 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
3812 }
3813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814 /*
3815 * Before spawning a new process, reset the time zone to be the system time zone.
3816 * This needs to be done because the system time zone could have changed after the
3817 * the spawning of this process. Without doing this this process would have the incorrect
3818 * system time zone.
3819 */
3820 TimeZone.setDefault(null);
3821
3822 /*
3823 * Initialize the default locale in this process for the reasons we set the time zone.
3824 */
3825 Locale.setDefault(data.config.locale);
3826
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003827 /*
3828 * Update the system configuration since its preloaded and might not
3829 * reflect configuration changes. The configuration object passed
3830 * in AppBindData can be safely assumed to be up to date
3831 */
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003832 applyConfigurationToResourcesLocked(data.config, data.compatInfo);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003833 applyCompatConfiguration();
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003834
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003835 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836
Romain Guya9582652011-11-10 14:20:10 -08003837 setupGraphicsSupport(data.info);
3838
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003839 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003840 * For system applications on userdebug/eng builds, log stack
3841 * traces of disk and network access to dropbox for analysis.
3842 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003843 if ((data.appInfo.flags &
3844 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003845 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3846 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003847 }
3848
3849 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003850 * For apps targetting SDK Honeycomb or later, we don't allow
3851 * network usage on the main event loop / UI thread.
3852 *
3853 * Note to those grepping: this is what ultimately throws
3854 * NetworkOnMainThreadException ...
3855 */
3856 if (data.appInfo.targetSdkVersion > 9) {
3857 StrictMode.enableDeathOnNetwork();
3858 }
3859
3860 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003861 * Switch this process to density compatibility mode if needed.
3862 */
3863 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3864 == 0) {
3865 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3866 }
Bob Leee5408332009-09-04 18:31:17 -07003867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3869 // XXX should have option to change the port.
3870 Debug.changeDebugPort(8100);
3871 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003872 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 + " is waiting for the debugger on port 8100...");
3874
3875 IActivityManager mgr = ActivityManagerNative.getDefault();
3876 try {
3877 mgr.showWaitingForDebugger(mAppThread, true);
3878 } catch (RemoteException ex) {
3879 }
3880
3881 Debug.waitForDebugger();
3882
3883 try {
3884 mgr.showWaitingForDebugger(mAppThread, false);
3885 } catch (RemoteException ex) {
3886 }
3887
3888 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003889 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 + " can be debugged on port 8100...");
3891 }
3892 }
3893
Robert Greenwalt434203a2010-10-11 16:00:27 -07003894 /**
3895 * Initialize the default http proxy in this process for the reasons we set the time zone.
3896 */
3897 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08003898 if (b != null) {
3899 // In pre-boot mode (doing initial launch to collect password), not
3900 // all system is up. This includes the connectivity service, so don't
3901 // crash if we can't get it.
3902 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3903 try {
3904 ProxyProperties proxyProperties = service.getProxy();
3905 Proxy.setHttpProxySystemProperty(proxyProperties);
3906 } catch (RemoteException e) {}
3907 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003910 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 appContext.init(data.info, null, this);
3912 InstrumentationInfo ii = null;
3913 try {
3914 ii = appContext.getPackageManager().
3915 getInstrumentationInfo(data.instrumentationName, 0);
3916 } catch (PackageManager.NameNotFoundException e) {
3917 }
3918 if (ii == null) {
3919 throw new RuntimeException(
3920 "Unable to find instrumentation info for: "
3921 + data.instrumentationName);
3922 }
3923
3924 mInstrumentationAppDir = ii.sourceDir;
3925 mInstrumentationAppPackage = ii.packageName;
3926 mInstrumentedAppDir = data.info.getAppDir();
3927
3928 ApplicationInfo instrApp = new ApplicationInfo();
3929 instrApp.packageName = ii.packageName;
3930 instrApp.sourceDir = ii.sourceDir;
3931 instrApp.publicSourceDir = ii.publicSourceDir;
3932 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003933 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003934 LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003936 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 instrContext.init(pi, null, this);
3938
3939 try {
3940 java.lang.ClassLoader cl = instrContext.getClassLoader();
3941 mInstrumentation = (Instrumentation)
3942 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3943 } catch (Exception e) {
3944 throw new RuntimeException(
3945 "Unable to instantiate instrumentation "
3946 + data.instrumentationName + ": " + e.toString(), e);
3947 }
3948
3949 mInstrumentation.init(this, instrContext, appContext,
3950 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3951
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003952 if (mProfiler.profileFile != null && !ii.handleProfiling
3953 && mProfiler.profileFd == null) {
3954 mProfiler.handlingProfiling = true;
3955 File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 file.getParentFile().mkdirs();
3957 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3958 }
3959
3960 try {
3961 mInstrumentation.onCreate(data.instrumentationArgs);
3962 }
3963 catch (Exception e) {
3964 throw new RuntimeException(
3965 "Exception thrown in onCreate() of "
3966 + data.instrumentationName + ": " + e.toString(), e);
3967 }
3968
3969 } else {
3970 mInstrumentation = new Instrumentation();
3971 }
3972
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003973 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08003974 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003975 }
3976
Christopher Tate181fafa2009-05-14 11:12:14 -07003977 // If the app is being launched for full backup or restore, bring it up in
3978 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003979 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 mInitialApplication = app;
3981
Christopher Tate75a99702011-05-18 16:28:19 -07003982 // don't bring up providers in restricted mode; they may depend on the
3983 // app's custom Application class
3984 if (!data.restrictedBackupMode){
3985 List<ProviderInfo> providers = data.providers;
3986 if (providers != null) {
3987 installContentProviders(app, providers);
3988 // For process that contains content providers, we want to
3989 // ensure that the JIT is enabled "at some point".
3990 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
3991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 }
3993
3994 try {
3995 mInstrumentation.callApplicationOnCreate(app);
3996 } catch (Exception e) {
3997 if (!mInstrumentation.onException(app, e)) {
3998 throw new RuntimeException(
3999 "Unable to create application " + app.getClass().getName()
4000 + ": " + e.toString(), e);
4001 }
4002 }
4003 }
4004
4005 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
4006 IActivityManager am = ActivityManagerNative.getDefault();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07004007 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
4008 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 Debug.stopMethodTracing();
4010 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004011 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 // + ", app thr: " + mAppThread);
4013 try {
4014 am.finishInstrumentation(mAppThread, resultCode, results);
4015 } catch (RemoteException ex) {
4016 }
4017 }
4018
Romain Guy65b345f2011-07-27 18:51:50 -07004019 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 Context context, List<ProviderInfo> providers) {
4021 final ArrayList<IActivityManager.ContentProviderHolder> results =
4022 new ArrayList<IActivityManager.ContentProviderHolder>();
4023
4024 Iterator<ProviderInfo> i = providers.iterator();
4025 while (i.hasNext()) {
4026 ProviderInfo cpi = i.next();
4027 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07004028 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 buf.append(cpi.authority);
4030 buf.append(": ");
4031 buf.append(cpi.name);
4032 Log.i(TAG, buf.toString());
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004033 IContentProvider cp = installProvider(context, null, cpi,
4034 false /*noisy*/, true /*noReleaseNeeded*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 if (cp != null) {
4036 IActivityManager.ContentProviderHolder cph =
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004037 new IActivityManager.ContentProviderHolder(cpi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 cph.provider = cp;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004039 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 }
4042 }
4043
4044 try {
4045 ActivityManagerNative.getDefault().publishContentProviders(
4046 getApplicationThread(), results);
4047 } catch (RemoteException ex) {
4048 }
4049 }
4050
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004051 public final IContentProvider acquireProvider(Context c, String name) {
4052 IContentProvider provider = acquireExistingProvider(c, name);
4053 if (provider != null) {
4054 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 }
4056
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004057 // There is a possible race here. Another thread may try to acquire
4058 // the same provider at the same time. When this happens, we want to ensure
4059 // that the first one wins.
4060 // Note that we cannot hold the lock while acquiring and installing the
4061 // provider since it might take a long time to run and it could also potentially
4062 // be re-entrant in the case where the provider is in the same process.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 IActivityManager.ContentProviderHolder holder = null;
4064 try {
4065 holder = ActivityManagerNative.getDefault().getContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004066 getApplicationThread(), name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 } catch (RemoteException ex) {
4068 }
4069 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004070 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 return null;
4072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004074 // Install provider will increment the reference count for us, and break
4075 // any ties in the race.
4076 provider = installProvider(c, holder.provider, holder.info,
4077 true /*noisy*/, holder.noReleaseNeeded);
4078 if (holder.provider != null && provider != holder.provider) {
4079 if (localLOGV) {
4080 Slog.v(TAG, "acquireProvider: lost the race, releasing extraneous "
4081 + "reference to the content provider");
4082 }
4083 try {
4084 ActivityManagerNative.getDefault().removeContentProvider(
4085 getApplicationThread(), name);
4086 } catch (RemoteException ex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 }
4088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 return provider;
4090 }
4091
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004092 public final IContentProvider acquireExistingProvider(Context c, String name) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004093 synchronized (mProviderMap) {
4094 ProviderClientRecord pr = mProviderMap.get(name);
4095 if (pr == null) {
4096 return null;
4097 }
4098
4099 IContentProvider provider = pr.mProvider;
4100 IBinder jBinder = provider.asBinder();
4101
4102 // Only increment the ref count if we have one. If we don't then the
4103 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004104 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004105 if (prc != null) {
4106 prc.count += 1;
4107 if (prc.count == 1) {
4108 if (localLOGV) {
4109 Slog.v(TAG, "acquireExistingProvider: "
4110 + "snatched provider from the jaws of death");
4111 }
4112 // Because the provider previously had a reference count of zero,
4113 // it was scheduled to be removed. Cancel that.
4114 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4115 }
4116 }
4117 return provider;
4118 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004119 }
4120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 public final boolean releaseProvider(IContentProvider provider) {
4122 if(provider == null) {
4123 return false;
4124 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004127 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004129 if (prc == null) {
4130 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004132 }
4133
4134 if (prc.count == 0) {
4135 if (localLOGV) Slog.v(TAG, "releaseProvider: ref count already 0, how?");
4136 return false;
4137 }
4138
4139 prc.count -= 1;
4140 if (prc.count == 0) {
4141 // Schedule the actual remove asynchronously, since we don't know the context
4142 // this will be called in.
4143 // TODO: it would be nice to post a delayed message, so
4144 // if we come back and need the same provider quickly
4145 // we will still have it available.
4146 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4147 mH.sendMessage(msg);
4148 }
4149 return true;
4150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 }
4152
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004153 final void completeRemoveProvider(IContentProvider provider) {
4154 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004155 String remoteProviderName = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004156 synchronized(mProviderMap) {
4157 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004158 if (prc == null) {
4159 // Either no release is needed (so we shouldn't be here) or the
4160 // provider was already released.
4161 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: release not needed");
4162 return;
4163 }
4164
4165 if (prc.count != 0) {
4166 // There was a race! Some other client managed to acquire
4167 // the provider before the removal was completed.
4168 // Abort the removal. We will do it later.
4169 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: lost the race, "
4170 + "provider still in use");
4171 return;
4172 }
4173
4174 mProviderRefCountMap.remove(jBinder);
4175
4176 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
4177 while (iter.hasNext()) {
4178 ProviderClientRecord pr = iter.next();
4179 IBinder myBinder = pr.mProvider.asBinder();
4180 if (myBinder == jBinder) {
4181 iter.remove();
4182 if (pr.mLocalProvider == null) {
4183 myBinder.unlinkToDeath(pr, 0);
4184 if (remoteProviderName == null) {
4185 remoteProviderName = pr.mName;
4186 }
4187 }
4188 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004189 }
4190 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004191
4192 if (remoteProviderName != null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004193 try {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004194 if (localLOGV) {
4195 Slog.v(TAG, "removeProvider: Invoking ActivityManagerNative."
4196 + "removeContentProvider(" + remoteProviderName + ")");
4197 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004198 ActivityManagerNative.getDefault().removeContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004199 getApplicationThread(), remoteProviderName);
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004200 } catch (RemoteException e) {
4201 //do nothing content provider object is dead any way
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004202 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004203 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205
4206 final void removeDeadProvider(String name, IContentProvider provider) {
4207 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004208 ProviderClientRecord pr = mProviderMap.get(name);
Jeff Brown2a4c5ac2011-08-23 11:58:26 -07004209 if (pr != null && pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004210 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004211 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004212 if (removed != null) {
4213 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 }
4216 }
4217 }
4218
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004219 /**
4220 * Installs the provider.
4221 *
4222 * Providers that are local to the process or that come from the system server
4223 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
4224 * Other remote providers are reference counted. The initial reference count
4225 * for all reference counted providers is one. Providers that are not reference
4226 * counted do not have a reference count (at all).
4227 *
4228 * This method detects when a provider has already been installed. When this happens,
4229 * it increments the reference count of the existing provider (if appropriate)
4230 * and returns the existing provider. This can happen due to concurrent
4231 * attempts to acquire the same provider.
4232 */
Romain Guy65b345f2011-07-27 18:51:50 -07004233 private IContentProvider installProvider(Context context,
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004234 IContentProvider provider, ProviderInfo info,
4235 boolean noisy, boolean noReleaseNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 ContentProvider localProvider = null;
4237 if (provider == null) {
4238 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004239 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 + info.name);
4241 }
4242 Context c = null;
4243 ApplicationInfo ai = info.applicationInfo;
4244 if (context.getPackageName().equals(ai.packageName)) {
4245 c = context;
4246 } else if (mInitialApplication != null &&
4247 mInitialApplication.getPackageName().equals(ai.packageName)) {
4248 c = mInitialApplication;
4249 } else {
4250 try {
4251 c = context.createPackageContext(ai.packageName,
4252 Context.CONTEXT_INCLUDE_CODE);
4253 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07004254 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 }
4256 }
4257 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004258 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 ai.packageName +
4260 " while loading content provider " +
4261 info.name);
4262 return null;
4263 }
4264 try {
4265 final java.lang.ClassLoader cl = c.getClassLoader();
4266 localProvider = (ContentProvider)cl.
4267 loadClass(info.name).newInstance();
4268 provider = localProvider.getIContentProvider();
4269 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004270 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 info.name + " from sourceDir " +
4272 info.applicationInfo.sourceDir);
4273 return null;
4274 }
Joe Onorato43a17652011-04-06 19:22:23 -07004275 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 TAG, "Instantiating local provider " + info.name);
4277 // XXX Need to create the correct context for this provider.
4278 localProvider.attachInfo(c, info);
4279 } catch (java.lang.Exception e) {
4280 if (!mInstrumentation.onException(null, e)) {
4281 throw new RuntimeException(
4282 "Unable to get provider " + info.name
4283 + ": " + e.toString(), e);
4284 }
4285 return null;
4286 }
4287 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004288 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 + info.name);
4290 }
4291
4292 synchronized (mProviderMap) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004293 // There is a possibility that this thread raced with another thread to
4294 // add the provider. If we find another thread got there first then we
4295 // just get out of the way and return the original provider.
4296 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 String names[] = PATTERN_SEMICOLON.split(info.authority);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004298 for (int i = 0; i < names.length; i++) {
4299 ProviderClientRecord pr = mProviderMap.get(names[i]);
4300 if (pr != null) {
4301 if (localLOGV) {
4302 Slog.v(TAG, "installProvider: lost the race, "
4303 + "using existing named provider");
4304 }
4305 provider = pr.mProvider;
4306 } else {
4307 pr = new ProviderClientRecord(names[i], provider, localProvider);
4308 if (localProvider == null) {
4309 try {
4310 jBinder.linkToDeath(pr, 0);
4311 } catch (RemoteException e) {
4312 // Provider already dead. Bail out of here without making
4313 // any changes to the provider map or other data structures.
4314 return null;
4315 }
4316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 mProviderMap.put(names[i], pr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 }
4319 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 if (localProvider != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004322 ProviderClientRecord pr = mLocalProviders.get(jBinder);
4323 if (pr != null) {
4324 if (localLOGV) {
4325 Slog.v(TAG, "installProvider: lost the race, "
4326 + "using existing local provider");
4327 }
4328 provider = pr.mProvider;
4329 } else {
4330 pr = new ProviderClientRecord(null, provider, localProvider);
4331 mLocalProviders.put(jBinder, pr);
4332 }
4333 }
4334
4335 if (!noReleaseNeeded) {
4336 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4337 if (prc != null) {
4338 if (localLOGV) {
4339 Slog.v(TAG, "installProvider: lost the race, incrementing ref count");
4340 }
4341 prc.count += 1;
4342 if (prc.count == 1) {
4343 if (localLOGV) {
4344 Slog.v(TAG, "installProvider: "
4345 + "snatched provider from the jaws of death");
4346 }
4347 // Because the provider previously had a reference count of zero,
4348 // it was scheduled to be removed. Cancel that.
4349 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4350 }
4351 } else {
4352 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 }
4355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 return provider;
4357 }
4358
Romain Guy65b345f2011-07-27 18:51:50 -07004359 private void attach(boolean system) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 sThreadLocal.set(this);
4361 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07004363 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004364 public void run() {
4365 ensureJitEnabled();
4366 }
4367 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4369 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4370 IActivityManager mgr = ActivityManagerNative.getDefault();
4371 try {
4372 mgr.attachApplication(mAppThread);
4373 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07004374 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 }
4376 } else {
4377 // Don't set application object here -- if the system crashes,
4378 // we can't display an alert, we just want to die die die.
4379 android.ddm.DdmHandleAppName.setAppName("system_process");
4380 try {
4381 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08004382 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 context.init(getSystemContext().mPackageInfo, null, this);
4384 Application app = Instrumentation.newApplication(Application.class, context);
4385 mAllApplications.add(app);
4386 mInitialApplication = app;
4387 app.onCreate();
4388 } catch (Exception e) {
4389 throw new RuntimeException(
4390 "Unable to instantiate Application():" + e.toString(), e);
4391 }
4392 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004393
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004394 ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004395 public void onConfigurationChanged(Configuration newConfig) {
4396 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004397 // We need to apply this change to the resources
4398 // immediately, because upon returning the view
4399 // hierarchy will be informed about it.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004400 if (applyConfigurationToResourcesLocked(newConfig, null)) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004401 // This actually changed the resources! Tell
4402 // everyone about it.
4403 if (mPendingConfiguration == null ||
4404 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
4405 mPendingConfiguration = newConfig;
4406
4407 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
4408 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004409 }
4410 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004411 }
4412 public void onLowMemory() {
4413 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004414 public void onTrimMemory(int level) {
4415 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004416 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417 }
4418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 public static final ActivityThread systemMain() {
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004420 HardwareRenderer.disable(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 ActivityThread thread = new ActivityThread();
4422 thread.attach(true);
4423 return thread;
4424 }
4425
Jeff Brown10e89712011-07-08 18:52:57 -07004426 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07004428 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 }
4430 }
4431
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004432 public int getIntCoreSetting(String key, int defaultValue) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004433 synchronized (mPackages) {
4434 if (mCoreSettings != null) {
4435 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004436 } else {
4437 return defaultValue;
4438 }
4439 }
4440 }
4441
Romain Guy65b345f2011-07-27 18:51:50 -07004442 public static void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004443 SamplingProfilerIntegration.start();
4444
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08004445 // CloseGuard defaults to true and can be quite spammy. We
4446 // disable it here, but selectively enable it later (via
4447 // StrictMode) on debug builds, but using DropBox, not logs.
4448 CloseGuard.setEnabled(false);
4449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 Process.setArgV0("<pre-initialized>");
4451
4452 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004453 if (sMainThreadHandler == null) {
4454 sMainThreadHandler = new Handler();
4455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456
4457 ActivityThread thread = new ActivityThread();
4458 thread.attach(false);
4459
Dianne Hackborn287952c2010-09-22 22:34:31 -07004460 if (false) {
4461 Looper.myLooper().setMessageLogging(new
4462 LogPrinter(Log.DEBUG, "ActivityThread"));
4463 }
4464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465 Looper.loop();
4466
Jeff Brown10e89712011-07-08 18:52:57 -07004467 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 }
4469}